【发布时间】:2016-09-25 11:41:06
【问题描述】:
出于性能原因,我正在尝试在我的组件上设置手动更改检测。
应用程序的结构:应用程序 -> 书籍 -> 页面
我在 AppComponent 中订阅了一个 observable,然后运行 ChangeDetectorRef 的“markForCheck”方法。
这似乎触发了 BookComponent(我标记为更新的组件的子组件)中的 ngAfterContentChecked 方法。
这让我相信父组件中的“markForCheck”也会更新所有子组件。
但是,即使在子组件(BookComponent)中执行了 ngAfterContentChecked,该组件的模板也不会更新!
我是否应该倾听每个孩子的 observable(有时在组件层次结构中的几个层次)?还是我做错了什么?以及为什么即使模板没有更新,ngAfterContentChecked 也会在子组件中执行?
一些相关代码。
@Component({
selector: 'app',
directives: [BookComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<book *ngIf="_book" [book]="_book" [style.height]="_availableDimensions.height+'px'" (window:resize)="onResize($event)"></book>
<footer id="footer"></footer>
`
})
export class PlayerComponent {
ngOnInit() {
this.initScale();
}
initScale(){
this._playerService.availableDimensions$.subscribe(
availableDimensions => {
// set local availableDimensions variable
this._availableDimensions = availableDimensions;
this._cd.markForCheck();
}
);
}
}
@Component({
selector: 'book',
directives: [PageComponent],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div id="pageScrollZone">
<div id="pageHolder" [ngStyle]="pageHolderStyles()"></div>
</div>
`
})
export class BookComponent {
constructor(
private _cd: ChangeDetectorRef,
private _playerService: PlayerService,
private _config: Config
){}
ngAfterContentChecked(){
// This part does execute when the observable changes
let date = new Date();
console.log('BOOK: '+date.getHours()+':'+date.getMinutes()+':'+date.getSeconds());
}
pageHolderStyles(){
// This part does NOT execute when the observable changes
let styles = {
marginTop: this._currentMargin.y+'px',
transform: 'scale('+ (this._baseZoom * this._currentZoomLevel) +')'
}
return styles;
}
}
【问题讨论】:
-
文字很便宜 - 给我们看一些代码 ;-) 理想情况下是一个允许复制的 plunker。
标签: angular observable angular2-changedetection