Checking for undefined in ngFor in Angular 6
We use ngFor loop in Angualr 6 for iterating through list of items.Before iterating we should check whether the collection used in the ngFor contains any elements.We can check if collection contains any elements by using the following syntax:
names is a string colllection defined as: names:string[];
We check if names is not undefined by just assigning the collection to *ngIf as:
<div *ngIf="names"> <div *ngFor="let name of names"> {{name}} </div> </div>
above loop will not print the names as names is undefined
Checking if collection consists of any elements
names:string[]; <div *ngIf="names.length>1"> <div *ngFor="let name of names"> {{name}} </div> </div>
the above loop will not print names as it doesn’t consist of any elements.
Now if we assign the names as:
names:string[]=['angular 2','angular 6']
then it will print:
angular 2
angular 6
Leave a Reply