Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access router outlet component from parent

Tags:

I have the following app root:

@Component({     selector: 'my-app',     providers: [],     templateUrl: `<button (click)="callChildFunction()">Close</button>                   <router-outlet></router-outlet>` }) export class AppComponent {      constructor() {      }      callChildFunction(){         // Call myFunction() here     }  } 

And here is my child (component used in the router-outlet):

@Component({     selector: 'child',     providers: [],     templateUrl: `<div>Hello World</div>` }) export class ChildComponent {      constructor() {      }      myFunction(){         console.log('success');     }  } 

I have discovered that I can use RouterOutlet to get the component functions but it doesn't seem accessible from within the app root.

How can I call myFunction() from the app root?

like image 831
ncohen Avatar asked Aug 16 '17 18:08

ncohen


People also ask

How do children access parent components?

We can get child component values in the parent component by creating a reference to the child component using the @ref directive in the Parent component. Using the reference instance, you can access the child component values in the parent.

Can you identify the use of router outlet directive?

The Router-Outlet #The Router-Outlet is a directive that's available from the router library where the Router inserts the component that gets matched based on the current browser's URL. You can add multiple outlets in your Angular application which enables you to implement advanced routing scenarios.


2 Answers

Make use of activate event for the same . Whenever we load a component in router outlet a activate event is emitted make use of that to get the component ref and call the respective method.

Parent Component

  <div class="container">     <router-outlet (activate)="onActivate($event)"></router-outlet>   </div> 

Template

  onActivate(componentRef){     componentRef.works();   } 

Child Comp

 works(){     console.log("works");   } 
like image 98
Rahul Singh Avatar answered Oct 04 '22 03:10

Rahul Singh


A small addition to @Rahul Singh great answer:

Make sure you check, which component instance is returned in the
(staying at Rahul's example) onActivate(componentRef) method,
and only call works(), if that component indeed has such method.

Example:

     onActivate(componentRef){        if(componentRef instanceof ChildWithWorksMethodComponent){          componentRef.works();          return;          }          console.log("This is not the ChildWithWorksMethodComponent");       }   

Otherwise, every time you navigate to a route, which component doesn't have such method, your console log will be full of errors like:

ERROR TypeError: componentRef.works is not a function

like image 41
Z3d4s Avatar answered Oct 04 '22 02:10

Z3d4s