简体   繁体   中英

ngIf can reference variable in nested ngFor in Angular 1.5. How to achieve the same in Angular 10?

The following code works in Angular 1.5. The <tr> element will only be rendered if the 'showFields' flag for that row key is enabled.

<table>
  <ng-container *ngIf="showFields[row.key]">
    <tr *ngFor="let row of rows">
      <td>{{row.key}}</td>
      <td>{{row.value}}</td>
    </tr>
  </ng-container>
</table>

Note that the 'row' variable from the ngFor is visible to the enclosing ngIf. This no longer works in Angular 2+ because the scope of the ngFor variable is now confined to the element. How could I achieve the same effect?

You could just switch the ngFor and ngIf , like so:

<table>
  <ng-container *ngFor="let row of rows">
    <tr *ngIf="showFields[row.key]">
        <td>{{row.key}}</td>
        <td>{{row.value}}</td>
    </tr>
  </ng-container>
</table>

Instead of using a separate showFields boolean array, you could also think about adding a new property showField to the row object, then you can simply check *ngIf="row.showField" , which prevents out of bounds exceptions.

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