2017-03-08 100 views
0

我試圖給一個元素添加一個類,並在一定時間後使用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後刪除新添加的內容。

請幫我解決這個問題。

回答

1

您此行this.className = newClassthis所指向的組件,但裏面超時this所指向的窗口使用ES6忽略這個

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

或存儲實例thisvm

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

兩者工作正常。

+0

謝謝,這個作品! – Body

0

由於函數作用域,'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() { 
    } 
} 
+0

我懷疑你會得到不能打電話的不確定 – yurzui

+0

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

+0

'this.image'在setTimeout函數中仍然未定義 –