Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 *ngIf not updating the HTML template

Tags:

angular

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);
  }
}
like image 317
takeradi Avatar asked Feb 07 '23 01:02

takeradi


1 Answers

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.

like image 75
dfsq Avatar answered Feb 13 '23 06:02

dfsq