好好爱自己!

Access viewchild from another component

https://stackoverflow.com/questions/50935728/access-viewchild-from-another-component

=================

 

I have two components, one videoComponent and videoControlsComponent. The video component contains a <video> element and the video component has some buttons to manipulate the videoComponent <video> element.

<video controls="{{ controls }}" [src]="streamUrl" #myVideo>
    Your browser does not support the video tag or the file format of this video.
</video>

videoComponent:

@ViewChild('myVideo') myVideo: any;
public playVideo() {
    this.myVideo.nativeElement.play();
}

videoControlComponent:

constructor(private videoComponent: VideoComponent) { }
public videoPlay() {
    this.videoComponent.playVideo()
}

The problem is that when I click the button I get the following error: Cannot read property 'nativeElement' of undefined at VideoControlsComponent.

But when I have exactly the same code but create the button not in the videoControlsComponent but videoComponent everything works fine.

Can you help me out please?

2

you need to use @ViewChild like you did with "myVideo" with videoComponent as well so like this @ViewChild(VideoComponent) videoComponent: VideoComponent

that's assuming videoComponent is a child of videoControls

if they are siblings you can use @Output to trigger an event in the parent, the parent would then change a boolean that is set to an input in videoControls and then set up ngOnChanges on videoControls to detect when that input changes

or you can set up a service to communicate between them. That might be the easiest option if they are not a parent-child relationship

Example of a Service to communicate between components:

@Injectable()
export class MyService {
    private myFunctionCallSource = new Subject();

    myFunctionCalled$ = this.myFunctionCallSource.asObservable();

    callMyFunction(){
        this.myFunctionCallSource.next()
    }
}

in videoComponent

this.myService.myFunctionCalled$.subscribe(
    res => this.myVideo.nativeElement.play(),
    err => console.log('MyService error', err)
);

in videoControlsComponent

this.myService.callMyFucnction()
posted @   立志做一个好的程序员  阅读(263)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
历史上的今天:
2018-05-09 ubuntu 卸载干净软件(包括配置文件)
2018-05-09 Unable to lock the administration directory (/var/lib/dpkg/) is another process using it?
2018-05-09 linux watch 命令

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示