How to change data in column based on condition on mat table

前端 未结 1 1361
自闭症患者
自闭症患者 2021-01-26 13:29

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\"

相关标签:
1条回答
  • 2021-01-26 14:09

    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>
    
    0 讨论(0)
提交回复
热议问题