How to call router outlet child component method from parent comonent

前端 未结 10 1973
甜味超标
甜味超标 2020-12-18 19:42

I am new to angular2


    

I have a button in parent component, if

10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-18 20:01

    After i searched a lot about this issue, i found a solution and wish it could help you. contentChild/ViewChild have no access to component(and it's data) that is loaded in router-outlet, and using sharedService needs an extra file and more code.

    You just need to read component that is loaded in the router outlet:

    1. Add template reference to your router outlet:

      
      
    2. Import the RouterOutlet from @angular/router :

      import {...
         RouterOutlet,
         ..} from "@angular/router";
      
    3. And finally, use it:

      @ViewChild("myRouterOutlet", { static: true }) routerOutlet: RouterOutlet;
      buttonClicked(){
          const childComp = this.routerOutlet.component as childComponent;
          childComp.childFunction();
      }
      

    Hope it could help you :)

提交回复
热议问题