takeradi
takeradi

Reputation: 3871

Angular 2 *ngIf not updating the HTML template

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

Answers (2)

Alexander Ciesielski
Alexander Ciesielski

Reputation: 10834

Remove the == true.

Ngif compares by default the expression to true.

Upvotes: 0

dfsq
dfsq

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

Related Questions