简体   繁体   中英

Can I put an ngIf else condition on a Angular Material table?

I've followed the Angular docs here https://angular.io/api/common/NgIf to create an NgIf else conditional over my Material Table. It is reading remote JSON file as API.

The API is twitter data and one of the fields I want to run condition on is 'replies'. If there are no replies, I want to replace the "0" with a "-".

I am getting the error

Can't have multiple template bindings on one element. Use only one attribute prefixed with * (" Replies ]*ngIf="hashtags.replies<1; else noReplies"> {{hashtags.replies}} "):`

So it seems I cannot run NgIf and interpolate my data in the same element, I've tried all kinds of combinations in the HTML but I am real stuck.

HTML

<ng-container matColumnDef="replies">
  <th mat-header-cell *matHeaderCellDef> Replies </th>
  <td mat-cell *matCellDef="let hashtags" *ngIf="hashtags.replies<1; else noReplies"> {{hashtags.replies}} </td>
  <ng-template #noReplies>-</ng-template>
</ng-container>

Try

    <ng-container matColumnDef="replies">
      <th mat-header-cell *matHeaderCellDef> Replies </th>
      <ng-container *matCellDef="let hashtags">
        <td mat-cell *ngIf="(hashtags.replies>0); else noReplies"> {{hashtags.replies}} </td>
      </ng-container>
      <ng-template #noReplies>-</ng-template>
    </ng-container>

The reason for getting this error is because your can't put 2 structural directives on the same DOM

In your code, you were using *matCellDef and *ngIf on the same <td> .

you can do it this way...... xd

<ng-container matColumnDef="estadoRevision">
    <mat-header-cell *matHeaderCellDef mat-sort-header>Revision</mat-header-cell>
    <mat-cell *matCellDef="let element">
        <td *ngIf="element.a === 0"> ejemplo </td>
        <td *ngIf="element.a === 1"> ejemplo </td>
    </mat-cell>
</ng-container>

有什么理由你不能直接在插值中做条件吗?

<td mat-cell *matCellDef="let hashtags">{{hashtags.replies > 0 ? hashtag.replies : '-'}}</td>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM