具有setTimeout的Angular 2更新类
我正在尝试向元素添加一个类,并在一段时间后使用setTimeout将其删除 组成部分 模板 我可以看到该函数添加了类名“foobar”,但它将永远保留。我希望这个函数在1500ms后删除新添加的具有setTimeout的Angular 2更新类,angular,ng-class,Angular,Ng Class,我正在尝试向元素添加一个类,并在一段时间后使用setTimeout将其删除 组成部分 模板 我可以看到该函数添加了类名“foobar”,但它将永远保留。我希望这个函数在1500ms后删除新添加的 请帮助我解决此问题。由于函数范围的原因,超时函数中未定义“this”,您将无法使用它。您可以使用如下箭头函数: setTimeout(()=> { this.className = '' }, 1500) this line this.className=newClass t
请帮助我解决此问题。由于函数范围的原因,超时函数中未定义“this”,您将无法使用它。您可以使用如下箭头函数:
setTimeout(()=> {
this.className = ''
}, 1500)
this line this.className=newClass this指向组件,但this inside timeout指向窗口。请使用ES6忽略此项
setTimeout(() => {
this.className = "";
}, 1500);
或将此实例存储到vm
两者都很好。将其更改为下面的代码即可。另外,有一个可以显示它工作的plunker
let $this = this;
setTimeout(function () {
$this.className = '';
}, 1500);
我怀疑您将无法调用未定义的类列表。我更新了我的解决方案@yurzui,它工作正常。“this.image”仍将在setTimeout函数中未定义。抱歉,请参阅更新
<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() {
}
}
setTimeout(() => {
this.className = "";
}, 1500);
let vm = this;
setTimeout(function() => {
vm.className = '';
}, 1500);
let $this = this;
setTimeout(function () {
$this.className = '';
}, 1500);