为什么这个组件在这个简单的砰砰声中
@Component({
selector: 'my-app',
template: `<div>I'm {{message}} </div>`,
})
export class App {
message:string = 'loading :(';
ngAfterViewInit() {
this.updateMessage();
}
updateMessage(){
this.message = 'all done loading :)'
}
}
扔:
例外:表达式'I'm {{message}} in App@0:5'在被检查后发生了变化。之前的值:'I'm loading:('。当前值:'I'm all done loading:)' in [I'm {{message}} in App@0:5]
当我所做的一切都是更新一个简单的绑定时,我的视图被启动?
你只需要在正确的生命周期钩子中更新你的消息,在这种情况下是ngAfterContentChecked而不是ngAfterViewInit,因为在ngAfterViewInit中对变量消息的检查已经开始但还没有结束。
看到的:
https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html !# afterview
所以代码就是:
import { Component } from 'angular2/core'
@Component({
selector: 'my-app',
template: `<div>I'm {{message}} </div>`,
})
export class App {
message: string = 'loading :(';
ngAfterContentChecked() {
this.message = 'all done loading :)'
}
}
查看工作演示在Plunker。
关于ExpressionChangedAfterItHasBeenCheckedError错误的一切你需要知道的文章详细解释了这种行为。
你设置的问题是ngAfterViewInit生命周期钩子是在变更检测处理DOM更新后执行的。你在这个钩子中有效地改变了模板中使用的属性,这意味着DOM需要重新渲染:
ngAfterViewInit() {
this.message = 'all done loading :)'; // needs to be rendered the DOM
}
这将需要另一个变更检测周期,而Angular在设计上只运行一个摘要周期。
你基本上有两种解决方法:
使用setTimeout, Promise异步更新属性。然后在模板中引用异步可观察对象
在DOM更新之前执行钩子中的属性更新- ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentChecked。