Search code examples
angularangular8angular-ng-if

Angular: ngIf behaviour with Img element while using setInterval


I have this image element

<img *ngIf="indicator" src="assets/on.gif" width="20px" height="20px">

Now, while declaring

indicator:boolean = false;

So by default I don't have the image

Now I have a button, if click on it, it will call a setInterval method

setInterval(this.setIndicator, 2000);

 setIndicator() {
    this.indicator = true;
    console.log(this.indicator);
  }

In console, I can see the value of this element as true, but it is not showing the img

If I set it true manually, it is reflecting that img. i.e

<img *ngIf="true" src="assets/on.gif" width="20px" height="20px">

Solution

  • You can try to use

    setInterval(()=>this.setIndicator(), 2000);
    

    Using an arrow function (()=>), you are binding the scope of this to the Componenent, and not the scope inside the setInterval.

    this.indicator inside the setInterval is not the same as your component's indicator. Using the arrow function solves this.

    This article can be helpful for more details