Understanding With NgFor Loop In Angular

ng-for loop

 
The ng-for loop is a structural directive. We will see how to change the structure of the dom.
 
Point is to repeat given HTML ones for each value in an array[]. Context is each time passing the array value for string interpolation or binding.
 
The syntax is *for =” let <value> of collection.”
 
<value> is a variable name, <collection.> is a property on your component which holds a collection, usually an array but anything that can be iterated.
 

Ng-For - local variable

  • Index - used to provide the index for the current element while iteration.
  • First - return true if the current element is the last in the iteration otherwise it is false.
  • Even - return true if current elements are even elements based on the index in the iteration otherwise false.
It is used to execute the block of code to a specific item number. A for loop is contains the initialization, condition, and increment/ decrement in a single line, which provides easy debug, and structure of looping.
  • The for loop is used to control the repeated statements.
  • A for loop is worked till the condition is (found)/matches successfully.
  • A for-loop id is used to repeat a portion of part of the HTML template once per item from an iterable list. 
Example
 
First, you have to create an application using the command " ng serve". Then open this project and then create a component using the command " ng g component loops". Go to the .ts file and take a variable array type. and then put the few values. Then go to the HTML file and make a list. Take a list item and then put the *ng-for loop. Then take put this variable name in the interpolation with the variable name like - {{student.name}}. 
 
Now save all the files. 
 
for-loop.html
  1. <h2><p>Understanding with Ng For loop</p></h2>    
  2. <h3><p>For loop in Angular</p></h3>    
  3.     
  4. <ul>    
  5.     <li *ngFor='let student of students;'>    
  6.       {{i+1}}    -     {{student.name}} - {{f}} - {{l}}   -{{ev}}   -   {{od}}    
  7. </ul>     
foor-loop.ts
  1. import {  
  2.     Component,  
  3.     OnInit  
  4. } from '@angular/core';  
  5. @Component({  
  6.     selector: 'app-loops',  
  7.     templateUrl: './loops.component.html',  
  8.     styleUrls: ['./loops.component.css']  
  9. })  
  10. export class LoopsComponent {  
  11.     students: any[] = [{  
  12.         'name''Chaman Gautam'  
  13.     }, {  
  14.         'name''Ravi Gautam'  
  15.     }, {  
  16.         'name''Mohit sharma'  
  17.     }, {  
  18.         'name''Gaurav Sharma'  
  19.     }, {  
  20.         'name''Gaurav Kumar'  
  21.     }, {  
  22.         'name''Sandeep singh'  
  23.     }, {  
  24.         'name''Sumit Nimmi'  
  25.     }, {  
  26.         'name''Deepak'  
  27.     }, {  
  28.         'name''Vikas'  
  29.     }];  
  30. }   
module.ts
  1. import { NgModule } from '@angular/core';  
  2. import { BrowserModule } from '@angular/platform-browser';  
  3.   
  4. import { AppRoutingModule } from './app-routing.module';  
  5. import {HttpClientModule } from '@angular/common/http'  
  6. import { AppComponent } from './app.component';  
  7. import { AddComponent } from './add/add.component';  
  8. import { RouterModule, Routes} from '@angular/router';  
  9. import{BookService } from './book.service';  
  10. import {InMemoryWebApiModule } from 'angular-in-memory-web-api';  
  11. import {TestData } from './testdata'  
  12.   
  13. import { FormsModule, ReactiveFormsModule } from '@angular/forms';  
  14. import { ShowdataComponent } from './showdata/showdata.component';  
  15. import { CommonModule } from '@angular/common';  
  16. import { IfelseComponent } from './ifelse/ifelse.component';  
  17. import { SwitchComponent } from './switch/switch.component';  
  18. import { LoopsComponent } from './loops/loops.component';  
  19. const routes: Routes = [  
  20.   {path:'', component:AddComponent},  
  21.   { path:'add', component:AddComponent}  
  22. ];  
  23.   
  24. @NgModule({  
  25.   declarations: [  
  26.     AppComponent,  
  27.     AddComponent,  
  28.     ShowdataComponent,  
  29.     IfelseComponent,  
  30.     SwitchComponent,  
  31.     LoopsComponent  
  32.   ],  
  33.   imports: [  
  34.     BrowserModule,  
  35.     AppRoutingModule,RouterModule.forRoot(routes),ReactiveFormsModule, FormsModule,  
  36.     HttpClientModule, CommonModule,  
  37.     InMemoryWebApiModule.forRoot(TestData)  
  38.   ],  
  39.   providers: [BookService],  
  40.   bootstrap: [ LoopsComponent]  
  41. })  
  42. export class AppModule { }  
mains.ts
  1. import { enableProdMode } from '@angular/core';    
  2. import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';    
  3. import { AppModule } from './app/app.module';    
  4. import { environment } from './environments/environment';    
  5. if (environment.production) {    
  6.   enableProdMode();    
  7. }    
  8. platformBrowserDynamic().bootstrapModule(AppModule)    
  9.   .catch(err => console.error(err));    
index.html
  1. <!doctype html>    
  2. <html lang="en">    
  3. <head>    
  4.   <meta charset="utf-8">    
  5.   <title>Dhwani</title>    
  6.   <base href="/">    
  7.   <meta name="viewport" content="width=device-width, initial-scale=1">    
  8.   <link rel="icon" type="image/x-icon" href="favicon.ico">    
  9. </head>    
  10. <body>    
  11.   <app-loops></app-loops>    
  12. </body>    
  13. </html>     
Now compile the project using the command " ng serve", after compiling this project you have to open the web browser and hit " localhost:4200" after few seconds you can see that your system shows the output like,
 
Understanding With NgFor Loop In Angular
 
Now you can see that all data will be display. 
 
Now use the indexing in the list.
 
index.html
  1. <h2><p>Understanding with Ng For loop</p></h2>    
  2. <h3><p>For loop in Angular</p></h3>    
  3.     
  4. <ul>    
  5.     <li *ngFor='let student of students; let i=index;'>    
  6.       {{i+1}}      
  7. </ul>    
Now save all the data and refresh the browser, and after refresh, the browser the output will be shown like,
 
Output
 
Understanding With NgFor Loop In Angular
 
Now you can see that there is a hit numbering that will be shown the number with each item.
 
Now use the true false and even odd for the last and first in the index like,
  1. <h2><p>Understanding with Ng For loop</p></h2>    
  2. <h3><p>For loop in Angular</p></h3>    
  3.     
  4. <ul>    
  5.     <li *ngFor='let student of students; let i=index; let f=first;     
  6. let l=last; let ev=even;let od=odd'>    
  7.       {{i+1}}    -     {{student.name}} - {{f}} - {{l}}      
  8. </ul>     
Now save all the data and refresh the browser, and after the refresh, the browser shows the output like below,
 
OUTPUT
 
Understanding With NgFor Loop In Angular
 
Now you can see that the output will be shown true false for the last and first value.
 
I hope you enjoy this article. Follow Chaman Gautam to learn more about angular and follow C# Corner to learning more about more technology.