首页 > 解决方案 > 使布尔变量在父范围内可用

问题描述

给定下面的组件

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(){}' 的范围内更新,但这并没有在整个组件的范围内更新。

我该如何解决?

标签: angularvideo.js

解决方案


您的非 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>

推荐阅读