Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
785 views
in Technique[技术] by (71.8m points)

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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: `
    <div>
      <h4>{{ user.name }}</h4>
      <h5>{{ user.age }} years old</h5>
      {{ user.location }} <br />
      {{ user.email }}

      <button (click)="update()">Internal update</button>
      <p>* should not update</p>
    </div>
  `
})
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: `
    <div>
      <h4>{{ user.name }}</h4>
      <h5>{{ user.age }} years old</h5>
      {{ user.location }} <br />
      {{ user.email }}

      <button (click)="update()">Internal update</button>
      <p>* should update</p>
    </div>
  `
})
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...