简体   繁体   中英

Angular2 OnPush change detection and ngFor

I have a parent component that displays a list of child components using ngFor . I noticed that performance gets really bad with increasing number of children so I have changed both to OnPush change detection strategy.

That helped a lot, but there are still few scenarios when it slows down and I can see thats due to change detection being executed for each of the children unnecessarily.

One example is when there is a click event inside the child component - even though no inputs is changed and its just triggering an animation, for some reason the change detection is being executed for parent component and as a result for each child component as well (even though the model behind ngFor doesnt change at all and its a OnPush strategy...). I would have thought that this kind of "isolated" event should only trigger change detection in that particular child component and not propagate up (I have actually tried event.stopPropagation() and event.preventDefault() with no success).

So I was wondering two things:

1) is there any way of having more control for what events change detection actually runs and whether it triggers the parent component change detecion as well?

2) is using "translate" pipes quite a lot in each child component (from ng2translate) could slow the application/change detection a lot?

Sample plunkr below to show what the problem is. Basically if I click on any of the item in ngFor list, it kicks of change detection for every single child rather than only the affected one and I was wondering if there is any way of suppressing that.

https://plnkr.co/edit/mD8HCbwq0cEwPt7itpCf

1) You can use ChangeDetectorRef.detach()

https://angular.io/docs/js/latest/api/core/index/ChangeDetectorRef-class.html#!#detach-anchor

Detaches the change detector from the change detector tree.

The detached change detector will not be checked until it is reattached.

This can also be used in combination with ChangeDetectorRef to implement local change detection checks.

2) pipes (if they are pure, which is the default) are only called when piped values or parameters change, therefore there is no performance disadvantage.

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