0 votes
in Angular by
How to set ngFor and ngIf on the same element?

1 Answer

0 votes
by

Sometimes you may need to both ngFor and ngIf on the same element but unfortunately you are going to encounter below template error.

 Template parse errors: Can't have multiple template bindings on one element.

In this case, You need to use either ng-container or ng-template. Let's say if you try to loop over the items only when the items are available, the below code throws an error in the browser

<ul *ngIf="items" *ngFor="let item of items">
  <li></li>
</ul>

and it can be fixed by

<ng-container *ngIf="items">
  <ul *ngFor="let item of items">
    <li></li>
  </ul>
</ng-container>
...