Search code examples
angularng-class

Angular 2 update class with setTimeout


I'm trying to add a class to an element and remove it after a certain time using setTimeout.

Component

export class setClass implements OnInit {
  className: string = ''

  setClassName(newClass) {
    this.className = newClass

    setTimeout(function () {
      this.className = ''
    }, 1500)
  }

  constructor() { }

  ngOnInit() {
  }
}

Template

<div>
    <img src="img/1.png" alt="" [ngClass]="className">
    <button (click)="setClassName('foobar')">Set new class</button>
</div>

I can see the function adds the class name 'foobar' but it stays forever. I'm expecting this function to remove the newly added after 1500ms.

Please help me fix this.


Solution

  • Your this line this.className = newClass the this is pointing to the component but the this inside timeout is pointing to the window use ES6 to ignore this

    setTimeout(() => {
      this.className = "";
    }, 1500);
    

    Or store instance of this to vm

    let vm = this;
    setTimeout(function() => {
      vm.className = '';
    }, 1500);
    

    both are working fine.