Friday, October 2, 2020

Angular ngFor example

 

What does ngFor in angular?

'ngFor' also structural directive behaves like a repeater for displaying list data in any list item. It is derived from ngForOf.In short, the collection of data rendering in the HTML list, table or div element through loop one by one. In the loop, we can perform the action of DOM manipulation like display, style, calculation, hide, show, etc.

Syntax of ngFor?

<ul *ngFor="let data of employee">
        <li>{{data.empid}}</li>
        <li>{{data.fullname}}</li>
        <li>{{data.city}}</li>
        <li>{{data.experience}}</li>
</ul>

Have you seen the above syntax?. We have declared employee array data as a local variable in the name of data using let statement. In angular let statement means  local variable. '*ngFor' is a template statement.

How to change table row background color alternatively using ngfor even odd?

angular ngfor example

employee = [
  {
    empid: 5623,fullname: "Stephen",city: "Newyork",experience: "5 years"  
  },
  { empid: 6523,fullname: "Michel",city: "london",experience: "7 years"
  },
  { empid: 6523,fullname: "peeter",city: "Dubai",experience: "8 years"
  },
  { empid: 7458,fullname: "stella",city: "Paris",experience: "4 years"
  }
];
*ngFor="let data of employee;let even = even; let odd = odd"
  • *ngFor - structural directive.
  • let data of employee - employee array data declared as a local variable(data) using let.
  • let even = even; let odd = odd; - even and odd which is inbuilt function returning true are false value and assigning value in a local variable using let statement.

Html code

<ng-container *ngFor="let data of employee;let even = even; let odd = odd">
            <tr class="evencls" *ngIf="even ==true; else oddtemplate"  >
                <td >{{data.empid}}</td>
            </tr>
            <ng-template #oddtemplate>
                <tr class="oddcls"  >
                        <td >{{data.empid}} </td>
                    </tr>
              </ng-template>
 </ng-container>
  • We have two-row(tr) both are having a different class for displaying different background colors.
  • In the first row have used ngif statement. If even true then display the current row otherwise displaying the #oddtemplate which contains the 'oddcls' class row.

Find the full code of above example.

ngfor.component.css

.evencls{
    background-color: cadetblue;
}
.oddcls{
    background-color: darkgoldenrod;
}

ngfor.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-ngfor',
  templateUrl: './ngfor.component.html',
  styleUrls: ['./ngfor.component.css']
})
export class NgforComponent implements OnInit {
 
  employee = [
  {
    empid: 5623,fullname: "Stephen",city: "Newyork",experience: "5 years"  
  },
  { empid: 6523,fullname: "Michel",city: "london",experience: "7 years"
  },
  { empid: 6523,fullname: "peeter",city: "Dubai",experience: "8 years"
  },
  { empid: 7458,fullname: "stella",city: "Paris",experience: "4 years"
  }
];
  constructor() { }
 
  ngOnInit() {
  }
 
}
 

ngfor.component.html

<table class="table" >
        <thead>
            <tr>
                <th scope="col">Employee Id</th>
                <th scope="col">Full Name</th>
                <th scope="col">City</th>
                <th scope="col">Experience</th>
            </tr>
        </thead>
        <tbody>
          <ng-container *ngFor="let data of employee;let even = even; let odd = odd">
            <tr class="evencls" *ngIf="even ==true; else oddtemplate"  >
                <td >{{data.empid}}</td>
                <td >{{data.fullname}}</td>
                <td>{{data.city}}</td>
                <td>{{data.experience}}</td>
            </tr>
            <ng-template #oddtemplate>
                <tr class="oddcls"  >
                        <td >{{data.empid}} </td>
                        <td >{{data.fullname}}</td>
                        <td>{{data.city}}</td>
                        <td>{{data.experience}}</td>
                    </tr>
              </ng-template>
        </ng-container>
        </tbody>
    </table> 

 How to display the index value of the array and verify the first and last record using *ngfor?

*ngFor="let data of employee;let indexid = index;let first = first; let last = last"
{{indexid}}
{{first}} || {{last}}
  • let indexid = index; - index returning index id.
  • let first = first; let last = last -first,last returning the true or false value.
  • Both are angular in-built features, Using ngfor we can achieve it.
  • Using interpolation displaying the index id, first, last value.

Find below the full code.

Index IdEmployee IdFull NameCityExperienceFirst or Last
05623StephenNewyork5 yearstrue || false
16523Michellondon7 yearsfalse || false
26523peeterDubai8 yearsfalse || false
37458stellaParis4 yearsfalse || true

ngfor.component.html

<table class="table" >
        <thead>
            <tr>
                <th scope="col">Index Id</th>
                <th scope="col">Employee Id</th>
                <th scope="col">Full Name</th>
                <th scope="col">City</th>
                <th scope="col">Experience</th>
                <th scope="col">First or Last</th>
            </tr>
        </thead>
        <tbody>
            <tr  *ngFor="let data of employee;let indexid = index;let first = first; let last = last"  >
                <td >{{indexid}}</td>
                <td >{{data.empid}}</td>
                <td >{{data.fullname}}</td>
                <td>{{data.city}}</td>
                <td>{{data.experience}}</td>
                <td>{{first}} || {{last}} </td>
            </tr>
        </tbody>
    </table> 

What does "trackBy"  and how to use "trackBy" in angular?

Before discussing "trackBy" we should know how the HTML control rendering in the view. For example, 100 records in the table. 100 times Dom will create row, cell and bind the value of that cell contains control. That is ok. But, if you are updating a single record in the table, again binding all table of records it's very expensive. For avoiding this performance issue angular providing the mechanism called "trackBy".
'trackBy' tracking the records which are already loaded in the dom and updating only modified records or newly created records only.

Refer below images developer console element section only last two-row only rerendered while clicking the update button.

angular ngfor trackby example

 <tr  *ngFor="let data of employee;trackBy: gettrackby;"  >
<button (click)="getemployeedata()" >Update</button>
gettrackby(empid:number,employees:any)
 {
    return employees.empid;
 }
  • We have created gettrackby function return empid and mapped against trackBy features.
  • When the page is loading 4 records will be displayed.
  • When you click the update button,getemployeedata function through updating existing array data and adding extra two more data in the array.In that, first 4 records are the same.
  • So using 'trackby' DOM will not recreate these 4 records. Dom will create only 2 records only. Total 6 records will be displayed in table.

ngfor.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-ngfor',
  templateUrl: './ngfor.component.html',
  styleUrls: ['./ngfor.component.css']
})
export class NgforComponent implements OnInit {
 
  employee = [
  {
    empid: 5623,fullname: "Stephen",city: "Newyork",experience: "5 years"  
  },
  { empid: 6523,fullname: "Michel",city: "london",experience: "7 years"
  },
  { empid: 6523,fullname: "peeter",city: "Dubai",experience: "8 years"
  },
  { empid: 7458,fullname: "stella",city: "Paris",experience: "4 years"
  }
];
  constructor() { }
 
  ngOnInit() {
  }
 
  getemployeedata()
  {
   this.employee = [
      {
        empid: 5623,fullname: "Stephen",city: "Newyork",experience: "5 years"  
      },
      { empid: 6523,fullname: "Michel",city: "london",experience: "7 years"
      },
      { empid: 6523,fullname: "peeter",city: "Dubai",experience: "8 years"
      },
      { empid: 7458,fullname: "stella",city: "Paris",experience: "4 years"
      },
      { empid: 8900,fullname: "John",city: "New jercy",experience: "3 years"
      },
      { empid: 9258,fullname: "kiara",city: "Tokyo",experience: "7 years"
      }
    ];
  }
 
  gettrackby(empid:number,employees:any)
  {
    return employees.empid;
  }
 
}
 

ngfor.component.html

<table class="table" >
            <thead>
                <tr>
                    <th scope="col">Employee Id</th>
                    <th scope="col">Full Name</th>
                    <th scope="col">City</th>
                    <th scope="col">Experience</th>
                </tr>
            </thead>
            <tbody>
                <tr  *ngFor="let data of employee;trackBy: gettrackby;"  >
                    <td >{{data.empid}}</td>
                    <td >{{data.fullname}}</td>
                    <td>{{data.city}}</td>
                    <td>{{data.experience}}</td>
                </tr>
            </tbody>
        </table> 
        <button (click)="getemployeedata()" >Update</button>

No comments:

Post a Comment

Lab 09: Publish and subscribe to Event Grid events

  Microsoft Azure user interface Given the dynamic nature of Microsoft cloud tools, you might experience Azure UI changes that occur after t...