Search code examples
angularmat-table

Using a method on a angular mat-cell


I would like to call a method inside a mat-cell:

<ng-container matColumnDef="complexity">
<th mat-header-cell *matHeaderCellDef> Complexidade</th>
<td mat-cell *matCellDef="let ep"> {{ getElemenaryProcessComplexity(ep) }} </td>
</ng-container>

The method getElementaryProcessComplexity is used to calculate a value on the server side and return a string.

The problem is that the method getElementaryProcessComplexity is called infinite times. enter image description here

Could someone help me? I want to calculate a value on server side and show this value in a mat-cell


Solution

  • This will run everytime change detection runs you want an observable.

    In your service have a method that returns an observable from the http call.

    getData() => this.http.get('dataUrl');
    

    and in you component expose it as an observable

    data$ = this.myService.getData();
    

    and in the template use the async pipe to view the data once it is available.

    <td mat-cell *matCellDef="let ep"> {{ data$ | async }} </td>
    

    or you could have a pipe that returns an observable for ep

    @Pipe({
      name: 'getElemenaryProcessComplexity'
    })
    export class GetElemenaryProcessComplexityPipe implements PipeTransform {
      constructor(private http: HttpClient) {}
    
      transform(ep): Observable<EpType> {
        return this.http.get('url/' + ep);
      }
    }
    
    

    and use it in the template with

    <td mat-cell *matCellDef="let ep"> {{ ep | getElemenaryProcessComplexity | async }} </td>
    

    The pipe will only create a single observable for each ep