带有setTimeout的Angular 2更新类

带有setTimeout的Angular 2更新类

问题描述:

我试图给一个元素添加一个类,并在一定时间后使用setTimeout删除它。带有setTimeout的Angular 2更新类

组件

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

    setClassName(newClass) { 
    this.className = newClass 

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

    constructor() { } 

    ngOnInit() { 
    } 
} 

模板

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

我可以看到函数将类名称 'foobar的',但它永远停留。我期待这个功能可以在1500ms后删除新添加的内容。

请帮我解决这个问题。

您此行this.className = newClassthis所指向的组件,但里面超时this所指向的窗口使用ES6忽略这个

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

或存储实例thisvm

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

两者工作正常。

+0

谢谢,这个作品! – Body

由于函数作用域,'this'未在您的超时函数中定义,您将无法使用它。您可以使用箭头功能是这样的:

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

<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() { 
    } 
} 
+0

我怀疑你会得到不能打电话的不确定 – yurzui

+0

我更新了我的解决方案@yurzui班级列表,它工作正常。 –

+0

'this.image'在setTimeout函数中仍然未定义 –

将其更改为下面的代码,它将工作。此外,有一个plunker https://plnkr.co/edit/oEfZOW?p=preview,显示它的工作

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