Search code examples
angularobservableangular2-changedetection

Angular - ChangeDetectionStrategy and subscription


I'm pretty new with Angular and I wanted to understand something.

I have a project where we keep:

 changeDetection: ChangeDetectionStrategy.OnPush

so if I want to keep the changeDetection onPush, how should I solve this issue: I have a list of objects in the view, and when you hover on one, there is a (mouseover) function that sends next() to the BehaviourSubject, to which I subscribe to get the hovered Object. If I put a console log with this subscription, in the console I will see the updated objects as I hover them.

But if I have in my component something like:

...
hoveredObject: ObjectType;

ngOnInit() {
  mySubscription.subscribe(s => {
  this.hoveredObject = s;
  });
}
...

In this case, only the first value I hover on will be displayed in the view, but not the other I hover on, and this gets fixed if I remove the onPush changeDetection.

But how can I overcome this without removing it? I understand that this is because the object is a reference and so the change is not detected, and I tried something like:

mySubscription.subscribe(s => {
  this.hoveredObject = { 
    id: s.id,
    name: s.name
  };

but it doesn't work and I get errors that name of undefined cannot be read, and this is because initially when you don't hover on anything the BehaviourSubject returns undefined.

How can I make Angular know there is a change here and make it update the view?

In the view I have a div with: {{hoveredObject}}

Thank you


Solution

  • OnPush can only make sense if we are talking about parent / child components communication. when the child has changeDetection: ChangeDetectionStrategy.OnPush setting and the parent is passing an object as an input to the child.

    If you want to handle events in the component which has its own state. It's good to avoid using onPush. If you want to use, you can manually call the Change detection manually using cdr.markforCheck().