Jacopo Sciampi
Jacopo Sciampi

Reputation: 3432

Component update issue

So I'm having this issue. I have a component that use the

changeDetection: ChangeDetectionStrategy.OnPush

the component have this logic :

ngOnInit(){
  this.serivce.something
  .subscribe( evt => {
    // Logic that update values of the array (the logic works)
  });
}

the html is something like that :

...
...
<div *ngFor="let item of myArray">
  <span *ngIf="item.showEye">TRUE</span>
  <span *ngIf="!item.showEye"> FALSE</span>
</div>
...
...

the problem is that, using this strategy, it won't render the component even if I have changed something. This is what the array looks like before doing the edits :

enter image description here

note that showEye is setted to true

Here's after the edit :

enter image description here

As you can see showEye is now false. But guess what? Nothing changed in the html.

So my question is, since I can't remove that strategy, how to "tell" the component to re-render it self?

Upvotes: 0

Views: 48

Answers (2)

Eduardo Vargas
Eduardo Vargas

Reputation: 9402

Angular has two types of ChangeDetectionStrategy the Default and the OnPush. The main difference is that OnPush only works with immutable objects and arrays. That is only if it is passed another reference the change detection of OnPush will be trigered. So it works very well with observables since you can handle any change of a variable as something like 'next; in a subject in which each change returns a new object and the previous object is discarded.

Example:

@Component({
  ....
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyOnPushComponent {
 person:Person = {
    name: 'Tom',
    age: 15
}

changeName(){
   this.person.name='Ralf'; // Doesnt triger the change detection of OnPush because it is the same reference (would be on default)
}



  changePerson(){
       this.person={
        name: 'Ted',
        age: 20
    }; // OnPush change detection is triggered because it refers to a new object
  }

}

Upvotes: 0

Batajus
Batajus

Reputation: 6257

To update your html try this:

constructor(private cd: ChangeDetectorRef) {...}

ngOnInit(){
    this.serivce.something
        .subscribe( evt => {
            // Logic that update values of the array (the logic works)
            this.cd.detectChanges(); // Triggers a change detection run
    });
} 

Because you have set the changeDetection to ChangeDetectionStrategy.OnPush you have disabled the automatic change detection, so you need to trigger it by yourself.

Upvotes: 1

Related Questions