How to change data in column based on condition on

2020-05-06 20:13发布

问题:

I am displaying data on mat table from rest api, In which there is a column "changeType" which displaying data in numeric form. Here it displaying "4" for "Add", and "1" for "Update". I want to display the proper word instead of number to make user more understandable. How can i achieve it?

<ng-container matColumnDef="changeType">
       <th mat-header-cell *matHeaderCellDef> Change Type </th>
       <td mat-cell *matCellDef="let element"> {{element.changeType}} </td>
</ng-container>

回答1:

You can do a function that take in input element.changeType and return the real value:

in html :

<ng-container matColumnDef="changeType">
       <th mat-header-cell *matHeaderCellDef> Change Type </th>
       <td mat-cell *matCellDef="let element"> {{resolveEnum(element.changeType)}} </td>
</ng-container>

in .ts

resolveEnum(num: number) {
  if(num == 1) 
   return "Update"
 else if(.....)
  .....
}

Obviously this is only an example you can make resolveEnum function better with switch case etc..

EDIT:

Thanks to @Drenai I made a batter solution, from the performance point of view.

I made a resolEnum pipe so:

Make the pipe:

@Pipe({
    name: 'resolveEnum'
})
export class ResolveEnum implements PipeTransform {

    constructor(private utility: UtilityService) { }

    transform(value: number): string {
        return this.utility.resolveEnum(value);
    }
}

where utilityService is a service where there is resolveEnum function.

In html:

<ng-container matColumnDef="changeType">
       <th mat-header-cell *matHeaderCellDef> Change Type </th>
       <td mat-cell *matCellDef="let element"> {{element | resolveEnum}} </td>
</ng-container>