切换视频(播放/暂停)时,我试图更改视频的自定义图标。
ngAfterViewInit() {
const vdoCont = document.querySelector('.video-player');
const vdo = vdoCont.querySelector('video');
vdo.addEventListener('play', () => {
console.log(this) // Here "this" refers to typescript class
this.updateVdoIcon(this);
});
vdo.addEventListener('pause', () => {
console.log(this) // Here "this" refers to typescript class
this.updateVdoIcon(this);
});
}
updateVdoIcon(videoElment: any) {
console.log(videoElment); // Expecting this to be video element instead of typescript class
}
我试图将箭头功能更改为JavaScript功能,但是在这里我不能使用我的“ updateVdoIcon”功能。
vdo.addEventListener('play', function() {
this.updateVdoIcon(this); // Property 'updateVdoIcon' does not exist on type 'HTMLVideoElement'
});
我知道我可以使用匿名函数(如下所示)并在那里更新图标,但是如果我想在函数中分离很多代码该怎么办
vdo.addEventListener('play', function() {
this.paused ? console.log('Play icon') : console.log('Pause icon')
});
您可以尝试这种方式,使用ElementRef
您可以访问元素,然后绑定事件。
源代码来自:https://stackoverflow.com/a/41610950/9380944答案。
import { AfterViewInit, Component, ElementRef} from '@angular/core';
constructor(private elementRef:ElementRef) {}
ngAfterViewInit() {
this.elementRef.nativeElement.querySelector('my-element')
.addEventListener('click', this.onClick.bind(this));
}
onClick(event) {
console.log(event);
}
在调用事件侦听器处理程序时,不会在Component的范围内调用它。因此,this
不返回组件,而是控制元素。
您需要将监听器与this
绑定。
vdo.addEventListener('play', (function() {
this.updateVdoIcon(this);
}).bind(this));
请参见文档here。
或者您可以捕获this
作为组件并传递给事件侦听器。
let self = this;
vdo.addEventListener('play', function() {
self.updateVdoIcon(this);
});
您可以在回调中传递event.currentTarget
,这将是您在其中定义事件监听器的元素:
vdo.addEventListener('play', (event) => {
this.updateVdoIcon(event.currentTarget);
});
在您的代码段中,this
将是箭头函数中的[[lexical this
。它从词法范围(即类实例)中捕获this
上下文。