简体   繁体   中英

ngFor is re-rendering the content on the change of observables

I am unable to find why ngFor re-renders the content of an array of Observable, whenever the value of any observable changes .

I tried to create an array of observables. There are 3 observable in the array. Unlike the other two observables, the third observable emits the values in the interval of 1 second .

Whenever the new value is emitted by the third observable, the ngFor re-iterates on the whole array . To verify this behaviour, I created a function to returns the count in increasing order. Whenever this 'getCount' method will be called from the template inside the ngFor, it will return the count and increase the count by one .

You can find the code here

I want to know why ngFor re-renders the whole content on the change of one observable and why angular is throwing the error " ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'null: 47245'. Current value: 'null: 47248'. "

It happens because by default angular keeps track of these objects using their object references and when we made some changes to the array we are returning new object references. So angular does not know whether it is old objects collection or not and that's why it destroys old list and then recreates them.

To avoid rerendering you can make use of trackBy function.

Stackblitz

Check the DOM elements while clicking Refresh Employees button.

And also here's a blog which clearly explains about it.

trackby-with-ngfor-directives-in-angular

You can also use trackBy in observables. I have made some modifications using your example and please concentrate on the developer tools and you can see only the observable gets rendered and it won't rerender the ngFor.

Observables with trackby => https://stackblitz.com/edit/angular-bbhmps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM