需要在组件中添加一个方法,以在用户第一次交互之后开始视频播放。
在组件中添加以下代码:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
@Component({ selector: 'app-video', templateUrl: './video.component.html', styleUrls: ['./video.component.css'] })
export class VideoComponent implements OnInit { @ViewChild('videoPlayer') videoplayer: ElementRef;
constructor() { }
ngOnInit() { }
ngAfterViewInit() {
this.videoplayer.nativeElement.muted = true;
this.videoplayer.nativeElement.play();
}
unmute() {
this.videoplayer.nativeElement.muted = false;
}
}
在模板文件中添加以下代码:
这里,“videoPlayer”是对元素的引用,它可以在代码中使用,让你得以控制视频的播放。在ngAfterViewInit生命周期钩子中,我们将视频设置为静音并立即播放。我们像这样定义了一个名为“unmute()”的函数,以在用户点击视频时取消静音。