Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trackBy with the async pipe

I am trying to use the async pipe with *ngFor to display an array of items acquired asynchronously.

<ul>
  <li *ngFor="let item of items | async; trackBy: trackPost">
    {{item.text}}
  </li>
</ul>

ngOnInit() {
  // very simple http call; returns an array of [{id: 1, text: "something"}]
  this.items = this.itemService.loadItems();
}
trackPost(index, item) { return item.id; }

This works fine. Then I want to add an item:

async addItem(text) {
  await this.itemService.addItem({text});
  // reload items after adding
  this.items = this.itemService.loadItems();
}

This also works, and it will update the items properly after it has been added.

The problem is that it will reload the entire array rather than just appending items. You can notice this with animations (if you animate items in). I know that I can handle the subscription on my own and work with an array, but I am wondering if there is a way to do this with the async pipe.

Is there a way for me to add the new item onto the existing observable? Failing that, is there a way to have the template properly track the items rather than think of them as being re-added?

like image 859
Explosion Pills Avatar asked Jun 28 '17 14:06

Explosion Pills


1 Answers

The problem is that you reassign the stream via this.items = this.itemService.loadItems();. So your Observable items does not emit new values, which Angular would track with your trackBy funciton, rather than you change the reference of the items, causing angular to do a full reload.

So just change your addItem-function of your service to emit the updated values to your previously gotten Observable via loadItems. After that you simply call

addItem(text) {
  this.itemService.addItem({text});
}

Example of a service:

@Injectable()
export class Service {
    private items: Array<string> = [];
    private items$ = new Subject<Array<string>>();

    loadItems(): Observable<Array<string>>  {
        return this.items$.asObservable();
    }

    addItem(text: string) {
        this.items = [...this.items, text];
        this.items$.next(this.items);
    }
}
like image 64
Leon Avatar answered Oct 19 '22 03:10

Leon