Changedetectionstrategy from the Angular

Asked

Viewed 102 times

1

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

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

I wonder if Angular 4+ has changed the way it updates the Components and whether it is interesting and performative to change the change detection strategy (Changedetectionstrategy) as needed.

If anyone has useful links on the issue I thank you already!

1 answer

1


The angular has two types of Changedetectionstrategy the Default and the Onpush. The main difference is that Onpush works only with immutable objects and arrays. That is only if another reference to change will be trigered. So it works very well with observables since you can treat 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
  }

 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.