×
BLUE
Angular TrackBy


Angular TrackBy
  7 August 2021
Read more Like this Post.
angular trackBy mean if array elements does not changed track by not update the DOM elements of in browser.
Example we have a array of animals.

_animals_: any[];
constructor(){
    this._animals_ = [
      { name: 'Shark', type: 'danger', age: 23 },
      { name: 'Lion', type: 'danger', age: 20 },
      { name: 'Bull', type: 'Not so', age: 12 },
      { name: 'Dino', type: 'danger', age: 32 },
      { name: 'Cat', type: 'no', age: 3 }
    ];
  }

in the code a variables array and set this variable value in the constructer.
which we call this array in our html page like this.
animal type total in zoo
{{ animals.name }} {{ animals.type }} {{ animals.in_zoo }}

and this is the table of the animals in a zoo which tbody tr have a for loop.
for printing all animals in array.
let set a button after table to set more data in table.
button have a function which name is setAnimals() let define this function.
setAnimals() : void {
    this._animals_ = [
      { name: 'Shark', type: 'Amrican', in_zoo: 23 },
      { name: 'Lion', type: 'African', in_zoo: 20 },
      { name: 'Bull', type: 'Pakistan', in_zoo: 12 },
      { name: 'Dino', type: 'Chinese', in_zoo: 32 },
      { name: 'Rhino', type: 'Russian', in_zoo: 32 },
      { name: 'buffalo', type: 'Japanese', in_zoo: 32 },
      { name: 'Cat', type: 'UK', in_zoo: 3 }
    ];
  }

this is the function which set more data in _animals_ array.
after click the button the page load more data in html page.
if we click the button this function call every time and html DOM elements update every time.
which can made page slower or crash the elements for this reason put a function which track the array if array have new items its include it otherwise its not refresh the DOM.

 trackAnimals(index: number, animals: any) : string{
    return animals.name;
  }

this function track the animals name if name is same its not include it in array. let make some changes in html.
 
      {{ animals.name }}
      {{ animals.type }}
      {{ animals.in_zoo }}
    
this is the tbody tr element of html page which we discuss before but its loop have new modifier ( trackBy ) and call the tracking function.
track function checking the animals.name on every button.

Related Post's

angular   angular-pipes   angular trackBy  
Not Loaded Zohaib Jozvi
0 7 August 2021
Read Latest Post.
Read other post.