【问题标题】:*ngIf behaviour: how to conditionally show data in angular 2?*ngIf 行为:如何有条件地以角度 2 显示数据?
【发布时间】:2016-04-06 10:34:57
【问题描述】:

这里是显示数据组件:

@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

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    您的问题不在于*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);
    

    【讨论】:

    • 你打败了我:D
    • @CosminAbabei 你会得到下一个 ;)
    • 我注意到,在控制台中,“超时后的 shoulShow 值”,this.shoulShow 仍然返回“false”(即使它在视图中为“true”)而“that.shoulShow”正确返回“真”(您提到的第二种解决方案)。知道为什么吗?
    • @Manube 是 console.log(...) 中的this.shoulShow 吗?因为应该是that.shoulShow
    • 使用 lambda 表示法,将 'shoullShow' 的值更改为 'true' 后,在控制台回调中仍然返回 'false';使用这个/那个技巧时似乎不会发生这种情况。我用你的第一个解决方案更新了 plunker,你可以检查控制台:plnkr.co/edit/a8UBQ76Af0YUFjreXuLX?p=preview
    猜你喜欢
    • 2017-08-23
    • 2020-08-27
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 2019-04-13
    • 1970-01-01
    相关资源
    最近更新 更多