Aev*_*ite 5 html video typescript angular2-template angular
我是 angular2 的新手,我一直在尝试访问组件内的 html5 视频标签。虽然我使用@ViewChild 装饰器访问视频标签,但我无法访问播放和暂停功能。我的 player.html 文件是
<video id="thisVideo" #videoplayer *ngIf="openPlayer" controls autoplay="autoplay" preload="auto" [poster]="src.thumbnailUrlHighRes" width="640">
<source [src]="src.videoURL" type="video/mp4" />
<p>Your browser does not support the video tag.</p>
</video>Run Code Online (Sandbox Code Playgroud)
视频的自动播放设置为 true。我需要使用空格键播放和暂停视频,为此我向主机组件添加了事件侦听器。但问题是我无法在事件侦听器中访问视频标签的播放和暂停功能。有人可以给我一些见解吗?
这个主题已经得到了解答,但我相信有一种更清晰的方法可以使用模板引用变量和ViewChild来实现此目的。
在模板中,您可以像这样引用您的视频,并使用#:
<video controls #myVideo>
<source src="http://my-url/video.mp4" type="video/mp4" />
Browser not supported
</video>
<a (click)="playVideo()">Play video</a>
Run Code Online (Sandbox Code Playgroud)
在你的 .ts 文件中:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.scss']
})
export class MyComponent implements OnInit {
@ViewChild('myVideo') myVideo: ElementRef; // Prior to Angular 8
// @ViewChild('myVideo', { static: true }) myVideo: ElementRef; => Angular 8
constructor() { }
ngOnInit() {
}
playVideo() {
/**
* You are accessing a dom element directly here,
* so you need to call "nativeElement" first.
*/
this.myVideo.nativeElement.play();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 1
我用这个工作了:
@HostListener('document:keyup', ['$event'])
onKeyUp(ev:KeyboardEvent) {
if(ev.code == "Space") {
let vid = <HTMLVideoElement>document.getElementById("thisVideo");
if(vid.paused) {
vid.play();
}
else {
vid.pause();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8969 次 |
| 最近记录: |