The *ngFor Directive in Angular

The *ngFor is a structural directive in Angular. The asterisk(*) present in *ngFor represents that it is a structural directive, which means this directive can shape/ reshape the UI.

The *ngFor directive is used to iterate over any iterable object like arrays.

export class AppComponent implements OnInit {
  countryList: Array<String>;
  ngOnInit(){
    this.countryList = ['India', 'USA', 'Brazil', 'France'];
  }
}
<div>
    <select>
        <option *ngFor="let country of countryList"> {{country}} </option>
    </select>
</div>

The result HTML will be:

<div>
    <select>
        <option> India </option>
        <option> USA </option>
        <option> Brazil </option>
        <option> France </option>
    </select>
</div>

Here countryList is an array of string values. When we use *ngFor on this array, it iterates over each element of the array and the current value of the array stores in “country”. How many values are present in the array, *ngFor creates that many <option> elements.

To track the index of the current element, we can store the index in one variable.

<select>
   <option *ngFor="let country of countryList; let i = index">
     {{i}} - {{country}}
   </option>
</select>

We can also access and store other values that are offered by *ngFor directive like first, last, even, and odd.

<div>
  <select>
     <option *ngFor="let country of countryList; let even=even" [class.evenOption]="even">
        {{country}} 
     </option>
  </select>
</div>

Now it won’t be a difficult task for you to show a collection of data stored in an array to the UI.

Leave a Reply

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