What Is *ngFor And *ngIf In Angular

Hello Friends, In this article, we are going to learn how to use *ngFor and *ngIf directive in angular application.

1 :- *ngFor directive is a built-in structural directive. it is used to loop over the data list and arrays to show the result on the front-end. it’s implemented with HTML template this directive goes through every item in the data collections. it shows the result when we pass the *ngFor  value in the double-curly braces.

2 :- *ngIf directive is used when you want to display or remove the element based on a condition. We defined the condition by passing an expression to the directive which is evaluated in the context of the host component. If the condition is true then add DOM Element else remove the DOM Element.

First I am creating  *ngFor example as the following type.

Step 1 :- Now let’s create a new Angular application using the below command.

ng new ngFor-Demo --routing

Step 2 :- Add the below code in app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ngFor-ngIf-demo';
  fruitsList=['Apple','Banana','Mango','Blueberry','Custard apple','Grapes']
}

Step 3 :- Add the below code in app.component.html

<h2>The Below Example Is ngFor</h2>
<div *ngFor="let frui of fruitsList">
    <td>I Like {{frui}}</td>    
</div>

Step 4 :- Let’s See Below Output.

Step 5 :- Now I am creating *ngIf example as the following type.

ng new ngIf-Demo --routing

Step 6 :- Add the below code in app.component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ngFor-ngIf-demo';
  fruitsList=['Apple','Banana','Mango','Blueberry','Custard apple','Grapes']  
}

Step 7 :- Add below code in app.component.html

<h2>The Below Example Is ngIf</h2>
<div *ngFor="let frui of fruitsList">
  <ng-template [ngIf]="frui=='Apple'">
    <td>I Love {{frui}}</td>
  </ng-template>    
</div>

Output

Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also Check What Is ngSwitch In Angular

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories