Search code examples
angularangular-ng-ifmat-tableangular12ng-switch

Angular , mat-table, html element toggle


How do I toggle between two html elements based on what value I have in Table column ? As Column value is loaded into dataSource variable and I am rendering it. So is there any way I can use column value to render a specific html .


Solution

  • If you wish that something would react on template based on what values are in the template table, that's doable. For example, I am going to access element.weight and when element value is > 10 I will render some HTML changes. In this case adding a green circle if its over 10 and a red one when < 10.

      <!-- Weight Column -->
      <ng-container matColumnDef="weight">
        <th mat-header-cell *matHeaderCellDef> Weight </th>
        <td mat-cell *matCellDef="let element"> {{element.weight}}
        <div *ngIf="element.weight >= 10" style="height: 10px; width: 10px; border-radius: 10px; background: green"></div>
        <div *ngIf="element.weight < 10" style="height: 10px; width: 10px; border-radius: 10px; background: red"></div>
        </td>
      </ng-container>
    

    Here is a working example: https://stackblitz.com/edit/angular-dhjzer?file=src%2Fapp%2Ftable-basic-example.html