我有两个组件,一个 videoComponent 和 videoControlsComponent。
视频组件包含 <video>
元素和视频组件有一些按钮来操作 videoComponent <video>
元素。
<video controls="{{ controls }}" [src]="streamUrl" #myVideo>
Your browser does not support the video tag or the file format of this video.
</video>
视频组件:
@ViewChild('myVideo') myVideo: any;
public playVideo() {
this.myVideo.nativeElement.play();
}
视频控制组件:
constructor(private videoComponent: VideoComponent) { }
public videoPlay() {
this.videoComponent.playVideo()
}
问题是,当我单击按钮时,出现以下错误:Cannot read property 'nativeElement' of undefined at VideoControlsComponent
.
但是当我有完全相同的代码但不是在 videoControlsComponent 而是在 videoComponent 中创建按钮时,一切正常。
你能帮我一下吗?
最佳答案
您需要像使用 videoComponent 中的“myVideo”一样使用 @ViewChild ,如下所示
@ViewChild(VideoComponent) videoComponent: VideoComponent
假设 videoComponent 是 videoControls 的子级
如果它们是 sibling ,您可以使用 @Output 触发父级中的事件,然后父级将更改设置为 videoControls 中输入的 bool 值,然后在 videoControls 上设置 ngOnChanges 以检测该输入何时发生变化
或者您可以设置一个服务来在它们之间进行通信。如果他们不是亲子关系,这可能是最简单的选择
组件之间通信的服务示例:
@Injectable()
export class MyService {
private myFunctionCallSource = new Subject();
myFunctionCalled$ = this.myFunctionCallSource.asObservable();
callMyFunction(){
this.myFunctionCallSource.next()
}
}
在视频组件中
this.myService.myFunctionCalled$.subscribe(
res => this.myVideo.nativeElement.play(),
err => console.log('MyService error', err)
);
在 videoControlsComponent 中
this.myService.callMyFucnction()
关于javascript - 从另一个组件访问 viewchild,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50935728/