angular - 使布尔变量在父范围内可用
问题描述
给定下面的组件
export class VideoPlayerComponent implements AfterViewInit {
@ViewChild('videoPlayer', { static: false })
videoPlayer: ElementRef;
@Input()
videoUrl: string;
@Input()
videoType: string;
/** Subject that emits when the component has been destroyed. */
@Output()
onPlayerEvent = new EventEmitter<VideoPlayerEvent>();
videoJsPlayer: videojs.Player;
showTimestamp: boolean = false;
timeStamp: string;
constructor() { }
ngAfterViewInit() {
if (this.videoUrl) {
const self = this;
this.videoJsPlayer = videojs(this.videoPlayer.nativeElement, {}, function () {
this.on('play', () => self.onPlayerEvent.emit('play'));
this.on('pause', () => self.onPlayerEvent.emit('pause'));
this.on('ended', () => self.onPlayerEvent.emit('ended'));
return hls;
});
const myButton = this.videoJsPlayer.controlBar.addChild("button");
const myButtonDom = myButton.el();
myButtonDom.innerHTML = "<i class=\"material-icons\">\n" +
"query_builder\n" +
"</i>";
// @ts-ignore
myButtonDom.onclick = function(){
console.log('click');
this.showTimestamp = !this.showTimestamp;
console.log(this.showTimestamp);
};
}
}
}
每当发生 onclick 事件时,我都会尝试切换“showTimestamp”变量。这似乎在 'function(){}' 的范围内更新,但这并没有在整个组件的范围内更新。
我该如何解决?
解决方案
您的非 Angular 方法存在一些问题。
主要问题是一个经典的 Javascript 问题 -this
在函数中声明为:function() { }
指的是函数本身。要引用外部范围,您应该使用箭头符号声明函数。
myButtonDom.onclick = () => {
console.log('click');
this.showTimestamp = !this.showTimestamp;
console.log(this.showTimestamp);
};
但是无论如何,您都不应该在 Angular 项目中手动操作 DOM。您将动态构建 HTML 并将点击事件绑定到 HTML 中的处理程序。
我不知道你的 HTML 要求是什么,但你会像这样绑定点击处理程序:
<button (click)="myClickHandler()">
Click me
</button>
推荐阅读
- javascript - 如何将 Typescript/Javascript 函数附加到 Puppeteer 页面上下文
- java - 为什么我在尝试输出数组时会收到异常错误?
- python - pygame 代码认为我输入了一个字符串,但它应该是一个表面
- amazon-web-services - 从 AWS S3 存储桶并行下载文件
- pandas - 在熊猫数据框中删除空值后出现键错误
- spring-boot - Spring Security 使用有效的客户端 ID 和客户端密码抛出 401 错误
- c# - 我想在我的 C# 项目中使用 System.Threading 加快计算速度
- sql - 我的 TO_DATE 似乎无法正常运行
- html - 需要修复将鼠标悬停在按钮上的问题?
- java - 使用循环后,我的扫描仪问题加倍,出现异常错误