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

3

这是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

1个回答

8
您的问题不在于*ngIf本身,而是在于setTimeout(function(){...}),因为匿名函数内部的this将指向函数本身,而不是AppComponent实例。
因此,为了能够访问AppComponent实例,请使用lambda表达式(也称为箭头函数)。
这是您的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);

你比我快一步了 :D - Cosmin Ababei
@CosminAbabei 你会得到下一个 ;) - Abdulrahman Alsoghayer
我注意到在控制台中,“shoulShow value after timeout”,this.shoulShow仍然返回“false”(即使在视图中它是“true”),而'that.shoulShow'正确返回“true”(你提到的第二个解决方案)。有任何想法为什么会这样? - Manube
@Manube,控制台中的console.log(...)应该是that.shoulShow,而不是this.shoulShow - Abdulrahman Alsoghayer
使用lambda符号后,当'shouldShow'的值更改为'true'时,在控制台回调中仍然返回'false';但是使用this/that技巧似乎不会发生这种情况。我已经使用您的第一个解决方案更新了plunker,您可以检查控制台:http://plnkr.co/edit/a8UBQ76Af0YUFjreXuLX?p=preview - Manube
@Manube 在你制作的 plunker 中,你忘记在 window.setTimeout(()=> 中加上 { 了,应该是 window.setTimeout(()=>{,我不得不说,这让我有一瞬间感到困惑 :) - Abdulrahman Alsoghayer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接