5

I'm playing with angular 2 alpha 44.

I have a tree model and use recursivity to display it. Each group contain 'Criterions', 'Segments' and others 'Groups'. We can delete and add all of these elements at any level.

There is a weird behavior when I remove elements and then add others on a same level. The new order is wrong, new elements got a bigger position property and array are sort on this property but they appears where elements were removed..

The new array is logged in the console and appears in the right order. And if you remove and add all the tree using the "SHOW/HIDE" button, the view is now in the right order.

You can see this behavior in this plunker and understand easily:

  1. Remove the first element
  2. Add a new element
  3. See that order in the view is not right and not identical as inside the console log
  4. Click 2 times on "SHOW/HIDE" button
  5. See that order in the view is now correct

Is there something like ng1 trackBy with ng2 NgFor? I found nothing about it inside sources..

bertrandg
  • 3,147
  • 2
  • 27
  • 35
  • I've added the pipe 'order', also didn't help...http://plnkr.co/edit/0ji4Xs2Z6Uxmk7k94Hrw?p=preview Very interesting issue. – punov Oct 27 '15 at 10:21
  • 2
    It seems to be an issue with the ` – Eric Martinez Oct 27 '15 at 12:03
  • thx @EricMartinez, you're right, it works with the other syntax. I found an [issue](https://github.com/angular/angular/issues/3442#issuecomment-151477046) on their repo and posted my plunker. – bertrandg Oct 27 '15 at 12:36

1 Answers1

3

trackBy was added in 2.0.0-beta.3

See also https://github.com/angular/angular/issues/4402

With template element:

@Component(
  template: `
   <template ngFor let-item [ngForOf]="items" [ngForTrackBy]=customTrackBy">
      {{item}}
   </template>
   `
)
class MyComponent {
  customTrackBy(index: number, obj: any): any {
    return index;
  }
}

With *ngFor:

@Component(
  template: `
   <div *ngFor="let item of items; trackBy:customTrackBy">
      {{item}}
   </div>
   `
)
class MyComponent {
  customTrackBy(index: number, obj: any): any {
    return index;
  }
}

See also https://github.com/angular/angular/issues/6872

I can either use the * *ngFor="let character of characters | async" *ngForTrackBy="customTrackBy"

or I can use *ngFor="let character of characters | async ; trackBy:customTrackBy"

See also Angular 2 ngModel bind in nested ngFor

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    what is ngForTrackBy for? – born2net Apr 14 '16 at 16:55
  • To guide `ngFor` about identity checking. If an array contains duplicates, `ngFor` doesn't work properly. With a custom `trackBy` the default behavior can be overridden. – Günter Zöchbauer Apr 14 '16 at 16:57
  • 1
    tx found what I needed: http://www.bennadel.com/blog/3020-understanding-object-identity-with-ngfor-loops-in-angular-2-beta-3.htm tx as always for the support... – born2net Apr 14 '16 at 19:58