There are three structural directives in angular
*ngIf
[ngSwtich]
*ngFor
1.*ngFor condition is similar to any other for the condition we used in other languages
In the below example *ngFor is added to the Select option element as below. in this example, colorSet is an array containing values of colors.
<option *ngFor="let color of colorSet" value="{{color.toLowerCase()}}"> {{color}} </option>
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', template: ` <h2> Welcome {{name}} </h2> <div> Please select Color </div> <select > <option *ngFor="let color of colorSet" value="{{color.toLowerCase()}}"> {{color}} </option> </select> `, styles: [` `] }) export class TestComponent implements OnInit { public name = "Amey Raut"; public colorSet = ["Red", "Blue", "Green","yellow"] constructor() { } ngOnInit() { } }
2. How to select the first element in the for loop (*ngfor)
Using “first as” in sentence we can get boolean value (true or false) to check if it is first loop or not.
<option *ngFor="let color of colorSet; first as firstElement" value="{{color}}">
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-test', template: ` <h2> Welcome {{name}} </h2> <div> Please select Color </div> <select > <option *ngFor="let color of colorSet; first as firstElement" value="{{color}}"> <ng-container *ngIf="firstElement"> This is first Element </ng-container> {{color}} </option> </select> `, styles: [` `] }) export class TestComponent implements OnInit { public name = "Amey Raut"; public colorSet = ["Red", "Blue", "Green","yellow"] constructor() { } ngOnInit() { } }
3. How to select the Last element in the for loop (*ngfor)
same as we did for first element we can use “last as” for last element in the for loop.
<option *ngFor="let color of colorSet; last as lastElement" value="{{color}}">{{color}} </option>
4. How to select the odd/even element in the for loop (*ngfor)
// For all Odd elements
<option *ngFor="let color of colorSet; odd as lastElement" value="{{color}}"> {{color}} </option>
// For all Even elements
<option *ngFor="let color of colorSet; even as lastElement" value="{{color}}"> {{color}} </option>