2017-09-23 79 views

回答

0

这是我在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)" width="100%" height="auto" controls> <source src="{{video.url}}" type="video/mp4"> </video> </div> </div>

  2. 在组件类:定义一个属性来保存当前正在播放的视频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(); 
          } 
         } 
        } 
    } 
    

希望这是明确的:)

感谢, 法迪