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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With