In Angular if you want to use two structural directives like *ngFor and *ngIf in the same element (like <div>, <tr>) that results in an error.
Can't have multiple template bindings on one element. Use only one attribute prefixed with *
How to use ngFor and ngIf on same element
It is very common to show only specific records while looping i.e. having ngIf to test a condition with in a ngFor loop or to loop elements only when a condition is true i.e. having ngFor within ngIf condition.
For example let’s say you have to iterate through Region objects using ngFor showing only those records where sales is greater than 200, writing it as given below results in error as both *ngFor and *ngIf are with in the same <tr> element.
<div class="container"> <table class="table table-sm table-bordered m-t-4 table-striped"> <thead> <tr> <th>Region</th> <th>Manager</th> <th>Sales (in millions)</th> </tr> </thead> <tbody> <tr *ngFor="let region of regions" *ngIf="region.sales > 200"> <td>{{region.region}}</td> <td>{{region.regionalManager}}</td> <td>{{region.sales}}</td> </tr> </tbody> </table> </div>
Best way to use ngFor and ngIf together is to use <ng-container>
element to write one of the structural directive. ng-container
allows us to create a separate section in a template without adding it to DOM. The ng-container does not get added to the DOM, but content
inside it is rendered.
With that change you can write ngFor and ngIf together as given below.
<tbody> <tr *ngFor="let region of regions"> <ng-container *ngIf="region.sales > 200"> <td>{{region.region}}</td> <td>{{region.regionalManager}}</td> <td>{{region.sales}}</td> </ng-container> </tr> </tbody>
That's all for this topic How to Use ngFor and ngIf in Same Element in Angular. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment