zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    使用_Capistrano_进行自动化部署(2)
    使用 Capistrano 进行自动化部署
    Zend_Framework_1 框架是如何被启动的?
    PHP新版本变化
    Phpstorm 无法自动断点 Exception
    理解希尔排序
    C# Thread 线程
    Unity 依赖注入容器的AOP扩展
    C# 面向切面编程 AOP
    C# 表达式树 Expression
  • 原文地址:https://www.cnblogs.com/oxspirt/p/10838802.html
Copyright © 2011-2022 走看看