How to fix *ngIf and *ngFor on same element causing error with Angular?

Sometimes, we want to fix *ngIf and *ngFor on same element causing error with Angular.

In this article, we’ll look at how to fix *ngIf and *ngFor on same element causing error with Angular.

How to fix *ngIf and *ngFor on same element causing error with Angular?

To fix *ngIf and *ngFor on same element causing error with Angular, we can move *ngIf to the ng-container component.

For instance, we write

<ng-container *ngIf="show">
  <div *ngFor="let thing of stuff">
    {{ log(thing) }}
    <span>{{ thing.name }}</span>
  </div>
</ng-container>

to use *ngIf in the ng-container component to show the div only when show is true.

And then we use *ngFor in the div to render the items in the stuff array.

Conclusion

To fix *ngIf and *ngFor on same element causing error with Angular, we can move *ngIf to the ng-container component.