为什么这个组件在这个简单的砰砰声中
@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]
当我所做的一切都是更新一个简单的绑定时,我的视图被启动?
在我的例子中,它发生在p-radioButton上。问题是,我使用的名称属性(这是不需要的)旁边的formControlName属性,就像这样:
<p-radioButton formControlName="isApplicant" name="isapplicant" value="T" label="Yes"></p-radioButton>
<p-radioButton formControlName="isApplicant" name="isapplicant" value="T" label="No"></p-radioButton>
我还将初始值“T”绑定到is申请人窗体控件,如下所示:
isApplicant: ["T"]
我通过删除单选按钮中的name属性来解决这个问题。
此外,因为2个单选按钮具有相同的值(T),这在我的情况下是错误的,简单地将其中一个值更改为另一个值(例如F)也解决了这个问题。
你只需要在正确的生命周期钩子中更新你的消息,在这种情况下是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。