What is ChangeDetectionStrategy in Angular2 and when to use OnPush Vs Default?

前端 未结 5 1510
故里飘歌
故里飘歌 2020-12-15 09:16

I happened to see ChangeDetectionStrategy in the ngrx documentation. It uses OnPush.

What is ChangeDetectionStrategy in Angula

5条回答
  •  孤街浪徒
    2020-12-15 10:10

    All above answers explain OnPush and Default, here I post an example about how it really works: https://plnkr.co/edit/hBYb5VOrZYEsnzJQF5Hk?p=preview

    user-one.component.ts :

    import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
    
    @Component({
      selector: 'user-one',
      changeDetection: ChangeDetectionStrategy.OnPush,
      template: `
        

    {{ user.name }}

    {{ user.age }} years old
    {{ user.location }}
    {{ user.email }}

    * should not update

    ` }) export class UserOneComponent { @Input() user; update() { this.user.name = 'Lebron James'; } }

    user-two.component.ts :

    import { Component, Input, ChangeDetectionStrategy } from '@angular/core';
    
    @Component({
      selector: 'user-two',
      changeDetection: ChangeDetectionStrategy.Default,
      template: `
        

    {{ user.name }}

    {{ user.age }} years old
    {{ user.location }}
    {{ user.email }}

    * should update

    ` }) export class UserTwoComponent { @Input() user; update() { this.user.name = 'Kevin Durant'; } }

    Every time we change object properties like 'this.user.email' or 'this.user.name', UserTwoComponent would always update the changes but UserOneComponent only change when we have a new user object.

    If you change the properties inside of each component, it inherit the ChangeDectectionStrategy, for instance, if we change this.user.name inside UserOneComponent both names in UserOneComponent and UserTwoComponent would change, but if we change name inside UserTwoComponent, only name inside UserTwoComponent would change

提交回复
热议问题