Reputation: 3871
Why is the *ngIf not updating the template? The title hello is always shown irrespective of the fact that isVisible changes to false after 2 seconds.
@Component({
selector: 'my-app',
template: `
<h1 *ngIf="isVisible == true">{{title}}</h1>
`
})
export class AppComponent {
title = 'Hello!';
isVisible = true;
constructor() {
setTimeout(function() {
this.isVisible = false;
console.log(this.isVisible);
}, 2000);
}
}
Upvotes: 4
Views: 3791
Reputation: 10834
Remove the == true.
Ngif compares by default the expression to true.
Upvotes: 0
Reputation: 193301
With anonymous function like this one
setTimeout(function() {
this.isVisible = false;
}, 2000);
execution context (this
) is pointing to global object (window
), however you want it to be AppComponent
instance. In this cases you would better use arrow function which preserve lexical scope:
constructor() {
setTimeout(() => {
this.isVisible = false;
}, 2000);
}
There are alternative approaches you could use, such as binding context with Function.prototype.bind and saving context reference, but arrow-functions are the most convenient in this case.
Upvotes: 8