我有一个简单的应用程序,其中包含侧面菜单的视频列表以及右侧的播放器。由于某些原因,我为列表和视频播放器制作了单独的组件。我想要的是,当用户单击列表中的任何项目时,相应的视频应在播放器中加载/播放。但是我无法更新src
元素的video
。
这是我的代码:
main-content.component.html
...
<mat-list *ngFor="let video of videos;let i = index">
<button (click)="setloadVid(video)" type="button">{{video.title}}</button>
</mat-list>
...
//Selector for playing video
<app-play-video></app-play-video>
...
main.component.ts
videos;
obs = new Subject<string>();
obs$ = this.obs.asObservable();
constructor(private vid: VideosService) {}
ngOnInit() {
this.videos = this.vid.VIDEOS;
//this is just to make sure that that the first video loads when the page loads.
this.obs.next("../../assets/secure-content/vid1.mp4");
}
setloadVid(video: any) {
this.obs.next(video.src);
}
我的播放器组件:
play-video.component.html
<div class="video-container video">
<video width="400px" height="300px" controls (click)="toggleVideo()" #videoPlayer>
<source [src]="src$ | async" type="video/mp4" /> Browser not supported
</video>
</div>
play-video.component.ts
@Component({
selector: 'app-play-video',
...
src$: Observable<string>;
constructor(private mainContPg: MainContentComponent) { }
ngOnInit() {
this.src$ = this.mainContPg.obs$;
}
该如何解决?谢谢!
答案 0 :(得分:1)
设置第二个组件的输入
<button (click)="currentVideo = video" type="button">{{video.title}}</button>
...
<app-play-video [video]="currentVideo"></app-play-video>
在组件中声明
videos;
currentVideo;
在第二个组件中,也声明它
@Input() video;
实施OnChanges
界面以更改视频的来源
export class PlayVideoComponent implement onChanges {
...
src;
ngOnChanges(changes: SimpleChanges) {
this.src = this.video.src;
}
...
}
并删除HTML的异步部分
<source [src]="src" type="video/mp4" /> Browser not supported
答案 1 :(得分:0)
问题与在模板中被调用的异步方法一起执行,该模板仅执行一次。而是在我的播放器组件中处理它。还可以使用BehaviorSubject并将第一个视频设置为默认视频。
视频;
obs = new BehaviorSubject<string>('../../assets/secure-content/vid1.mp4');
obs$ = this.obs.asObservable();
组件:
@Component({
selector: 'app-play-video',
...
src$: Observable<string>;
constructor(private mainContPg: MainContentComponent) { }
ngOnInit() {
this.mainContPg.obs$.subscribe((vsrc)=>{
this.src = vsrc;
});
}