Mat*_*ood 5 angular2-changedetection angular
https://stackblitz.com/edit/angular-xpamld
问题:有人可以帮助我理解为什么我的原型changeDetection: ChangeDetectionStrategy.OnPush仍然允许我更新内部值name吗?如果这不是ChangeDetectionStrategy.OnPush应该阻止的,它应该做什么?
app.component.ts:
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
public name = 'Angular 5';
public changeName() {
this.name = 'Outer';
}
}
Run Code Online (Sandbox Code Playgroud)
app.component.html:
<hello name="{{ name }}"></hello>
<button (click)="changeName()">Outter Change</button>
<p>{{name}}-- outer</p>
<p>
Start editing to see some magic happen :)
</p>
Run Code Online (Sandbox Code Playgroud)
你好.component.ts:
@Component({
selector: 'hello',
template: `<h1>Hello {{name}}!</h1> <button (click)="changeName()">inner Change</button>`,
styles: [`h1 { font-family: Lato; }`],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HelloComponent {
@Input() name: string;
public changeName() {
this.name = 'Inner';
}
}
Run Code Online (Sandbox Code Playgroud)
因为原始数据类型是不可变的 - 如果您更改它,它的引用也会更改,因此ChangeDetectorRef您的组件知道它必须检测更改(因为OnPush查找引用更改,而不是数组、对象中的数据突变)。如果你想避免这种情况的原语,您可以手动禁用/激活此与ChangeDetectorRef实例detach()/ reattach():
import { ChangeDetectorRef } from '@angular/core';
export class HelloComponent {
@Input() name: string;
constructor(private ref: ChangeDetectorRef) {}
public changeName() {
this.ref.detach();
this.name = 'Inner';
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6261 次 |
| 最近记录: |