0

I have this data. How to display in table when service value is true? Something like this below.

Table should be:

ID     Services
5      service1,service3

Data:

  {   
    id: 5, 
    services:
    { 
       service1: true, 
       service2: false, 
       service3: true, 
    }
  }

html

      <ng-container matColumnDef="id"> 
        <mat-header-cell *matHeaderCellDef mat-sort-header>QTY</mat-header-cell>
        <mat-cell *matCellDef="let purchaseOrder">{{purchaseOrder.id}}</mat-cell>
      </ng-container>

     <ng-container matColumnDef="services"> 
        <mat-header-cell *matHeaderCellDef mat-sort-header>Equipment Ordered</mat-header-cell>
        <mat-cell *matCellDef="let purchaseOrder">{{purchaseOrder.services}}</mat-cell>
      </ng-container>

1 Answer 1

2

You can use a custom method in your component that filters the services:

getRequiredServices(servicesObject) {
 return Object.keys(servicesObject).filter(service => servicesObject[service]).join();
}

and in your HTML:

<ng-container matColumnDef="services">
  <mat-header-cell *matHeaderCellDef mat-sort-header>Equipment Ordered</mat-header-cell>
  <mat-cell *matCellDef="let purchaseOrder">{{getRequiredServices(purchaseOrder.services)}}</mat-cell>
</ng-container>

update

Modify the method this way fr what you asked in the comments(return a string which has all the truthy properties):

getRequiredServices(servicesObject) {
  return Object.entries(servicesObject).reduce(
    (requiredServices, [key, value]) => {
      if (typeof value === 'boolean' && value) {
        requiredServices.push(key);
      } else if (typeof value === 'string' && value) {
        requiredServices.push(value);
      }
      return requiredServices;
    },
    []
  ).join();
}
Sign up to request clarification or add additional context in comments.

8 Comments

Hello, nothing is showing on the table. also is it checking if the value is true or false? thanks
@user10860402 - Yes, it should return the services that are true.
It worked now thank you. do you mind if i asked a follow up question? what if i have another property inside services that is "services4: 'string here' ". how can i also show the value of string if it is not null? thank you
@user10860402 - If the new property has a string as its value then the function will work without any changes because a string is a true value.
i mean show the value of the string if it is not null or empty?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.