如何访问根组件以获取更改属性?
问题:
我有不同的模板(默认和自定义页面),这些模板具有不同的结构。我希望控件通过根组件(AppComponent)类中的自定义参数呈现进程。
举个例子:
app.component.html:
<div>
<div id="wrapper">
<div *ngIf="!customPage">
<div id="page-wrapper">
<div class="container-fluid">
<router-outlet></router-outlet>
</div>
</div>
</div>
<div *ngIf="customPage">
<router-outlet></router-outlet>
</div>
</div>
</div>
app.component.ts:
export class AppComponent{
customPage: boolean;
constructor() {
this.customPage = false;
}
}
我尝试从 custom.page.ts:
访问export class CustomComponent implements AfterViewChecked {
constructor(private rootComponent: AppComponent) {
}
ngAfterViewChecked(): void {
this.rootComponent.customPage = true;
}
}
但我检索错误:
ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.
我尝试使用其他生命周期事件,但在所有事件中,我都会检索此错误。
而且,我认为这个解决方案并不好。也许Angular2有解决这个问题的方法吗?
感谢。
答案 0 :(得分:1)
避免此错误的一种简单方法是等待勾选,例如使用setTimeout
。
setTimeout(() => this.rootComponent.customPage = true)