- ngfor trackby in angular


 

App.component.html:

<h1>Welcome to {{title}}</h1>

<h2>ngFor with trackby Tutorial</h2>

 

<table>

  <tr>

    <td>Book id</td>

    <td>Book name</td>

    <td>Book price</td>

 

  </tr>

  <tr *ngFor="let item of booklist;trackBy:trackbybooklistid">

    <td>{{item.id}}</td>

    <td>{{item.name}}</td>

    <td>{{item.price}}</td>

  </tr>

</table>

<button (click)="getbooklist()">Add one extra book </button>

 

App.component.ts

export class AppComponent {

     title='Shubho Tech'

     booklist:any[];

     constructor(){

       this.booklist=[

         {

           id:1,

           name:"Depth in C",

           price:350

         },

         {

          id:2,

          name:"Depth in C++",

          price:450

        },

        {

          id:3,

          name:"Java programming",

          price:550

        },

        {

          id:4,

          name:"Python programming",

          price:850

        }

       ];

     }

 

     getbooklist():void{

      this.booklist=[

        {

          id:1,

          name:"Depth in C",

          price:350

        },

        {

         id:2,

         name:"Depth in C++",

         price:450

       },

       {

         id:3,

         name:"Java programming",

         price:550

       },

       {

         id:4,

         name:"Python programming",

         price:850

       },

       {

        id:5,

        name:"Database Management",

        price:650

      }

 

      ];

     }

     trackbybooklistid(index:number,booklist:any):string{

       return booklist.id

     }

}




Post a Comment

Previous Post Next Post