Welcome Guest! (App Version 3.1)

websitnero logo name

*ngFor

Usage of *ngFor

ngFor directives is helpful for looping through a set of values and then rendering 'n' number of html elements for each value that holds true in the expression before it.

Practical Examples of *ngFor

Please follow the mentioned steps:

  1. Create a compennt named 'home'
  2. Add the home component in the app.component.html file removing all boilerplate code there.
  3. Create an Array for Students in logic file (.ts) along with data containing - name, country, age of 5 people. We will use this data to loop in the view (.html) file.

home.component.html

<ul *ngFor="let x of students">
  <li style="background:blue" *ngIf="x.country == 'USA'">
    {{x.name}}, {{x.country}}, {{x.age}}
  </li>
</ul>

home.component.ts


import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  students = [
    {name: 'Robert', country: 'USA', age: 27},
    {name: 'Lily', country: 'UK', age: 17},
    {name: 'Jacob', country: 'USA', age: 19},
    {name: 'Rose', country: 'Canada', age: 31},
    {name: 'Gilbert', country: 'China', age:47}
  ];

  constructor() { }

  ngOnInit() {
  }

}
  1. You'll get the following result.

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.