这是show-data组件:
@Component({
selector: 'show-data',
template: `yes! Now showing the show-data directive template !`
})
export class ShowData {}
以及它的父级元素:
@Component({
selector: 'my-app',
template: `
The 'shouldShow' boolean value is: {{shouldShow}}
<show-data *ngIf="shouldShow"></show-data>
<div *ngIf="!shouldShow">NOT showing the show-data directive template</div>
`,
directives: [ShowData]
})
export class App {
shouldShow:boolean = false;
constructor(){
console.log("shouldShow value before timeout",this.shouldShow);
window.setTimeout(function(){
this.shouldShow = true;
console.log("shouldShow value after timeout",this.shouldShow);
}, 1000);
}
}
最初,shouldShow
变量被设置为 false,而 show-data
指令模板不会显示。没问题。
shouldShow
然后在父组件构造函数中一秒后被设置为'true'。
为什么 shouldShow
的值没有在父组件视图中更新?
这里是一个 plunkr
console.log(...)
应该是that.shoulShow
,而不是this.shoulShow
。 - Abdulrahman Alsoghayerwindow.setTimeout(()=>
中加上{
了,应该是window.setTimeout(()=>{
,我不得不说,这让我有一瞬间感到困惑 :) - Abdulrahman Alsoghayer