播放视频应该停止 html、角度应用程序中的所有其他视频

Dev*_*emi -1 html html5-video angular

我有一个 Angular 应用程序,正在加载一些带有 html5 视频标签的视频,我一次只需要播放一个视频。

小智 6

这是我在Angular2 应用程序中的做法。

  1. 在组件 HTML 中,绑定一个事件(playing)="onPlayingVideo($event)",以便稍后在类组件中您可以处理逻辑。
    `<div *ngFor='let video of videoList; let i=index' class="video">
        <div class="video_player">
            <video (playing)="onPlayingVideo($event)" controls>
                <source src="{{video.url}}" type="video/mp4">
            </video>
        </div>
    </div>
Run Code Online (Sandbox Code Playgroud)
  1. 在组件类中:定义一个属性来保存当前播放的视频currentPlayingVideo: HTMLVideoElement;。并定义您的事件侦听器方法,您将在其中处理我的案例中的逻辑,我称之为它onPlayingVideo(event)。简单地说,每次用户播放新视频时,只需暂停旧视频并播放新选择的视频即可。所以你的类应该如下所示:
        export class VideoListComponent implements OnInit {
            
            currentPlayingVideo: HTMLVideoElement;
            
            constructor() { }
            ngOnInit() { }
            
            onPlayingVideo(event) {
                event.preventDefault();
                // play the first video that is chosen by the user
                if (this.currentPlayingVideo === undefined) {
                    this.currentPlayingVideo = event.target;
                    this.currentPlayingVideo.play();
                } else {
                // if the user plays a new video, pause the last 
                // one and play the new one
                    if (event.target !== this.currentPlayingVideo) {
                        this.currentPlayingVideo.pause();
                        this.currentPlayingVideo = event.target;
                        this.currentPlayingVideo.play();
                    }
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

希望这是清楚的:)

谢谢,法迪