how to use track by inside ngFor angular 2

前端 未结 5 1718
天命终不由人
天命终不由人 2020-11-28 11:59

tried every syntax i can guess couldnt make it works !



{{post|json}}
         


        
5条回答
  •  萌比男神i
    2020-11-28 12:08

    Just want to add few examples (Angular 2+) in addition to others' answer to make the use of trackBy clear.

    From documentation:

    To avoid this expensive operation, you can customize the default tracking algorithm. by supplying the trackBy option to NgForOf. trackBy takes a function that has two arguments: index and item. If trackBy is given, Angular tracks changes by the return value of the function.

    Read more here: https://angular.io/api/common/NgForOf

    An example will explain it better.

    app.component.ts

       array = [
          { "id": 1, "name": "bill" },
          { "id": 2, "name": "bob" },
          { "id": 3, "name": "billy" }
       ]
    
       foo() {
          this.array = [
             { "id": 1, "name": "foo" },
             { "id": 2, "name": "bob" },
             { "id": 3, "name": "billy" }
          ]
       }
    
       identify(index, item) {
          return item.id;
       }
    

    Let's display the array into 3 div using *ngFor.

    app.component.html

    Example of *ngFor without trackBy:

    {{e.id}} - {{e.name}}

    What happend if we click on foo button ?

    → The 3 divs will be refreshed. Try it yourself, open your console to verify.

    Example of *ngFor with trackBy:

    {{e.id}} - {{e.name}}

    What happend if we click on foo button ?

    → Only the first div will be refreshed. Try it yourself, open your console to verify.

    And what if we updated the first object instead of the whole object ?

       foo() {
          this.array[0].name = "foo";
       }
    

    → There is no need to use trackBy here.

    It's especially usefull when using Subscription which often looks like what I schematized with array. So it would looks like:

       array = [];
       subscription: Subscription;
    
       ngOnInit(): void {
          this.subscription = this.fooService.getArray().subscribe(data => {
             this.array = data;
          });
       }
    
       identify(index, item) {
          return item.id;
       }
    

提交回复
热议问题