Angular 2 How to Use ngif Use *ngIf with*ngFor


Example

While you are not allowed to use *ngIf and *ngFor in the same div (it will gives an error in the runtime) you can nest the *ngIf in the *ngFor to get the desired behavior.

Example 1: General syntax

<div *ngFor="let item of items; let i = index">
  <div *ngIf="<your condition here>">

   <!-- Execute code here if statement true -->

  </div>
</div>

Example 2: Display elements with even index

<div *ngFor="let item of items; let i = index">
  <div *ngIf="i % 2 == 0">
    {{ item }}
  </div>
</div>

The downside is that an additional outer div element needs to be added.

But consider this use case where a div element needs to be iterated (using *ngFor) and also includes a check whether the element need to be removed or not (using *ngIf), but adding an additional div is not preferred. In this case you can use the template tag for the *ngFor:

<template ngFor let-item [ngForOf]="items">
    <div *ngIf="item.price > 100">
    </div>
</template>

This way adding an additional outer div is not needed and furthermore the <template> element won't be added to the DOM. The only elements added in the DOM from the above example are the iterated div elements.

Note: In Angular v4 <template> has been deprecated in favour of <ng-template> and will be removed in v5. In Angular v2.x releases <template> is still valid.