To understand ngFor lets create a new Angular project using angular CLI
Write the below contents in app.component.html file
<h2>List of colors</h2> <ul *ngFor="let color of colors"> <li>{{color}}</li> </ul> <h2>Displaying colors using index of ngFor</h2> <div *ngFor="let color of colors; let i = index"> <p>{{i+1}} - {{color}}</p> </div>
Write the below contents into app.component.ts file
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'ngForDemo'; colors = ['Read','Yellow','Blue','Green']; }
After running the code on server the output will look like below :
Example 2: Fetching data using Observables
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
app.component.ts
import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit{ title = 'DemoNgFor'; names = ['Hello']; colors = ['Read', 'Yellow', 'Blue', 'Green']; ngOnInit(): void { this.getDataFromApi(); } constructor(private http: HttpClient){} getDataFromApi(){ this.http.get<[]>('/assets/data/listUsers.json').subscribe( (response) => {console.log('Response ' + response); this.names = response; }, (error) => {console.log(error); }, () => {console.log('Completed'); } ); } }
listUsers.json
[ "Tyson", "Justin", "Martin" ]
app.component.html
<select> <option *ngFor="let name of names; let i = index" [value]="name"> {{name}} </option> </select>
Output :