ngFor in Angular2
Hey...!! It's been a while since I posted my last article in CodeCircle. In web development,when fetching data from the database we use for loops basically.Use of for loops can be easily done using *ngFor in AngularJS. Lets see how we can easily use this in implementation.
Set up your Angular environment as we did in previous articles. Now lets try simple examples to get aclear idea of using *ngFor.
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public fruits = ['Apple', 'Grapes', 'Lemon', 'Oranges', 'Papaw'];
}
Now write the code for the *ngFor in your app.components.html file.
Set up your Angular environment as we did in previous articles. Now lets try simple examples to get aclear idea of using *ngFor.
Example 1 :Print Set of fruits
Define an array of fruits in your app.components.ts file as below.import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public fruits = ['Apple', 'Grapes', 'Lemon', 'Oranges', 'Papaw'];
}
Now write the code for the *ngFor in your app.components.html file.
<p *ngFor="let item of this.fruits">{{item}}</p>
Output of the above code is given belowExample 2 :Printing Nested Arrays
Here yo can easily print nested arrays as given below. In your app.component.ts ,
public data = [['jane', '23', '21'], ['John', '32', '45'], ['Kate', '10', '5']];
And the *ngFor will be called as below,
<p *ngFor="let item of this.data">{{item[0]}} | {{item[1]}} | {{item[2]}}</p>
Output is given below.
Example 3 :Calculations
Also you can easily do mathematical operations as given below using the same example above.Lets see how to multiply two numbers in the array.
<h3>Multiplication</h3>
<p *ngFor="let item of this.data">{{item[0]}} - {{item[1]*item[2]}}</p>
Hope you could get a basic idea on *ngFor. See you soon with another article.
Comments
Post a Comment