Access router outlet component from parent

Viewed 14060

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?

4 Answers

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

For more infomation, you can access the variable of ChildComponent as well.

Child Comp

export class ChildComponent {
    my_var= true;
}   

Parent Component

// Template

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


  onActivate(componentRef){
    console.log(componentRef.my_var);
  }
Related