【问题标题】:Making boolean variable available in parent scope使布尔变量在父范围内可用
【发布时间】:2020-03-18 18:34:57
【问题描述】:

给定下面的组件

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 video.js


    【解决方案1】:

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

    【讨论】:

    • 嗨,这方面的帮助,stackoverflow.com/questions/60745796/…,谢谢
    • 请不要为您自己的无关问题寻求帮助。您现在至少对我的 3 个答案执行了此操作。我第一次回答说我会尽可能避免使用材料。那是因为我对Material不熟悉,而且我不喜欢框架。我和许多其他人一样关注开放的 Angular 问题。您的问题可能还没有得到满意的回答,因为它不够清楚。不过,我担心向其他答案发送垃圾邮件对您没有帮助。
    • 我看开放性问题有两个原因。 1) StackOverflow 多年来帮助了我很多。我想帮助其他正在学习的人。 2)识别他人的问题并给出明确的解决方案有助于我提高自己的技能。我喜欢这样做。如果我必须努力去理解一个不费吹灰之力或令人困惑的问题,我已经知道不值得我花时间尝试解决发帖人的要求,因为这会导致不满意的体验。我在这里没有指责你的任何事情,我只是在解释我的一般推理。
    • 最近看了数百个问题,我可以给你一些关于什么是好问题的建议。 1) 做你的研究并提供证据 2) 尝试将你的问题抽象成最简单的例子。不要只是复制和粘贴您的项目代码。这也将帮助您了解您的问题。 3) 给出问题的清晰分解和解决方案的要求。
    猜你喜欢
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 2015-08-21
    相关资源
    最近更新 更多