*ngIf 行为:如何有条件地显示 angular 2 中的数据?

*ngIf behaviour: how to conditionally show data in angular 2?

这里是显示数据组件:

@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

您的问题不在 *ngIf 本身。它在 setTimeout(function(){...}) 上,因为匿名函数内部的 this 将引用函数本身而不是 AppComponent 实例。

因此,改为能够访问 AppComponent 实例。使用 lambda expression(也称为箭头函数)。

这是您plunker编辑的

window.setTimeout(()=>{
   this.shoulShow = true;
   console.log("shoulShow value after timeout",this.shoulShow);
}, 1000);

或者,您可以将 this 分配给一个新变量,以便能够从匿名函数内部访问它。

let that = this
window.setTimeout(function(){
   that.shoulShow = true; // here use the new var 'that' instead of 'this'
   console.log("shoulShow value after timeout",that.shoulShow);
}, 1000);