Friday, June 16, 2023

How to Use ngFor and ngIf in Same Element in Angular

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

  1. Angular ngSwitch Directive With Examples
  2. Angular ngStyle Directive With Examples
  3. Angular ngClass Directive With Examples
  4. Angular Event Binding With Examples
  5. Angular First App - Hello world Example

You may also like-

  1. Angular @Output() Decorator With Examples
  2. Angular Form setValue() and patchValue()
  3. Passing Query Parameters in Angular Routing
  4. Angular + Spring Boot JWT Authentication Example
  5. Difference Between HashMap And ConcurrentHashMap in Java
  6. Private Methods in Java Interface
  7. How to Create Deadlock in Java
  8. Global Keyword in Python With Examples

No comments:

Post a Comment