什么是Angular2中的ChangeDetectionStrategy以及何时使用OnPush Vs Default?

won*_*rld 7 angular

我碰巧ChangeDetectionStrategyngrx文档中看到了.它使用OnPush.

什么是ChangeDetectionStrategyAngular2,以及何时使用OnPush Vs Default?

Hai*_*ang 12

以上所有的答案解释OnPushDefault,这里我发表一下到底是如何工作的例子: 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';
  }
}
Run Code Online (Sandbox Code Playgroud)

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';
  }
}
Run Code Online (Sandbox Code Playgroud)

每次我们更改"this.user.email"或"this.user.name"等对象属性时,UserTwoComponent将始终更新更改,但UserOneComponent仅在我们有新用户对象时更改.

如果更改每个组件内部的属性,它会继承ChangeDectectionStrategy,例如,如果我们在U​​serOneComponent中更改this.user.name,UserOneComponent和UserTwoComponent中的两个名称都会更改,但如果我们更改UserTwoComponent中的名称,则只有UserTwoComponent内的名称才会更改


Rom*_*n C 5

OnPush如果对象是不可变的,并且不更改组件中对象的状态,请使用策略。在对象的每次更改都使运行更改检测器解决更改的情况下,它将执行得比默认情况更好。变更检测策略:OnPush中或多或少地描述了相似之处

为了通知Angular我们将遵守前面提到的条件以提高性能,我们将使用OnPush变更检测策略

Angular文档说

变更检测策略:

  • OnPush表示CheckOnce在水合作用期间将更改检测器的模式设置为。

  • Default表示CheckAlways在水合作用期间将更改检测器的模式设置为。

  • 什么是“水合”? (2认同)

小智 5

这个例子可以帮助你理解:

\n\n

更改检测策略 onpush

\n\n

angular2-with-immutablejs-and-redux

\n\n
\n

那么当事件被触发时到底会发生什么呢?在 Angular 1.x 中,当触发摘要循环时,整个应用程序中的每个绑定都会被触发。类似地,在 Angular 2 中,也会检查每个组件。现在,告诉 Angular 仅当组件的输入属性之一发生变化(而不是每次发生事件时)才对组件运行更改检测,这不是很酷吗?我们可以在组件级别使用 Angular\xe2\x80\x99s ChangeDetectionStrategy。

\n
\n\n

OnPush 只关注输入属性,Default 检查所有属性。

\n


小智 5

我在那个链接中看到了一个非常好的和简单的解释:

http://www.codecompiled.com/change-detection-in-angular-2/

ChangeDetectionStrategy.OnPush:它只会在特定情况下更新视图:
* 触发某些事件时。
* 当输入值改变时。

Default 意思是:总是更新视图。

  • 上面指定的内容之上的“始终”是什么? (3认同)