0

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.

Body
  • 3,608
  • 8
  • 42
  • 50

4 Answers4

1

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.

Babar Hussain
  • 2,917
  • 1
  • 17
  • 14
0

'this' is not defined in your timeout function because of function scope and you'll not be able to use it. You can use an arrow function like this:

setTimeout(()=> {
      this.className = ''
    }, 1500)
0
<div>
    <img src="img/1.png" #image alt="">
    <button (click)="setClassName('foobar')">Set new class</button>
</div>

export class setClass implements OnInit {
  className: string = ''
  @ViewChild("image") image ;
  setClassName(newClass) {
    this.image.nativeElement.classList.add(newClass)
    let self = this;
    setTimeout(function () {
      self.image.nativeElement.classList.remove(newClass)
    }, 1500)
  }

  constructor() { }

  ngOnInit() {
  }
}
El houcine bougarfaoui
  • 35,805
  • 9
  • 37
  • 37
0

Change it to the code below and it will work. Also, have a plunker https://plnkr.co/edit/oEfZOW?p=preview that shows it working

let $this = this;
setTimeout(function () {
    $this.className = '';
}, 1500);
nekkon
  • 107
  • 1
  • 6