ChangeDetectionStrategy Angular

1

While studying Angular 6 I was seeing that it has different strategies of how the component is updated according to the Events, XHR and Observables within my application.

After much research I did not find any content in Portuguese about this issue.

I would like to know if Angular 4+ has changed the way it updates the components and if it is interesting and performative to change the ChangeDetectionStrategy strategy as needed.

If someone has useful links about the issue already thank you!

    
asked by anonymous 12.09.2018 / 20:00

1 answer

1

Angle has two types of ChangeDetectionStrategy and Default and 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 one is discarded.

Example:

@Component({
  ....
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MeuOnPushComponent {
     pessoa:Pessoa = {
        nome: 'Jose',
        idade: 15
    }

    mudarNome(){
       this.pessoa.nome='Joao'; // Nao triger a change detection do OnPush pois a referencia e a mesma (seria detectado no default)
    }

   mudarPessoa(){
       this.pessoa={
        nome: 'Joao',
        idade: 20
    }; // Triger a change detection do OnPush pois a referencia muda para um novo objeto
  }

 }
    
13.09.2018 / 16:27