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?
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.
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.
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"); }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With