带有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 = newClass
的this
所指向的组件,但里面超时this
所指向的窗口使用ES6忽略这个
setTimeout(() => {
this.className = "";
}, 1500);
或存储实例this
至vm
let vm = this;
setTimeout(function() => {
vm.className = '';
}, 1500);
两者工作正常。
答
由于函数作用域,'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() {
}
}
答
将其更改为下面的代码,它将工作。此外,有一个plunker https://plnkr.co/edit/oEfZOW?p=preview,显示它的工作
let $this = this;
setTimeout(function() {
$this.className = '';
}, 1500);
谢谢,这个作品! – Body