繁体   English   中英

Angular @ViewChild():ElementRef 未定义(HTML 视频元素)

[英]Angular @ViewChild(): ElementRef is undefined (HTML video element)

我的@ViewChild('video') 视频有问题!:ElementRef; 未定义。 我有一个嵌入视频的页面。 视频是从 API 获取的,它是 .mp4 格式。 我需要将 currentTime 设置为我的视频,所以它不应该从头开始播放。

我也尝试了 ngAfterViewInit() 并且它是相同的,即使在 ngAfterViewInit 中也没有加载视频。

但是我找到了一个可行的解决方案,但它与 setTimeout 一起使用,我不想使用它,因为我猜这不是一个合适的解决方案。

我的代码是:HTML:

<main class="page" *ngIf="videoLoaded">
  <div class="bg-gray" *ngIf="isLoaded">
    <div class="container">
      <div class="video-div {{ slide.count == 0 ? 'full-width' : '' }}">
        <div class="video-parent">
          <video
            id="lecture-video"
            controls
            #video
          >
            <source [src]="videoUrl" />
          </video>
        </div>  
      </div>     
    </div>
  </div>
  <div class="spinner-parent" *ngIf="!isLoaded">
    <app-spinner></app-spinner>
  </div>
</main>

打字稿:

 private isVideoLoaded$!: BehaviorSubject<boolean>;
  @ViewChild('video') video!: ElementRef;

 constructor(
    ...
  ) {
    this.isVideoLoaded$ = new BehaviorSubject<boolean>(false);
  }

 ngOnInit(): void {
    this.videoLoadedSubs = this.isVideoLoaded$.subscribe((data: boolean) => {
      this.videoLoaded = data;
      console.log(data);
      if (this.videoLoaded) {
        setTimeout(() => {
          this.isPageLoaded = true;
          this.video.nativeElement.currentTime = 500;
        }, 100);
      }
    });

    this.videoApiSubs= this.videoService
      .getVideo(this.id)
      .subscribe((videoData: Video) => {
        this.videoData= videoData;
        this.videoUrl = this.videoData.video;

        this.lectureLoaded = true;
        this.isVideoLoaded$.next(true);
      });
  }

如果我删除那个 setTimeout 我得到那个视频是未定义的..我不知道我什至可以尝试什么了..

因为您使用的是*ngIf ,所以在执行ngOnInitngAfterViewInit时,渲染的模板没有元素video 尝试使用[hidden]而不是*ngIf并使用ngAfterViewInit

这是因为*ngIf="videoLoaded"*ngIf="isLoaded"

视频元素可能未加载。 您需要像这样添加{ static: false }

@ViewChild('video', { static: false }) video!: ElementRef;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM