Parent Access Router Output Component

I have the following application 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 (the component used in router-outlet):

@Component({
    selector: 'child',
    providers: [],
    templateUrl: `<div>Hello World</div>`
})
export class ChildComponent {

    constructor() {

    }

    myFunction(){
        console.log('success');
    }

}

I found that I can use RouterOutlet to get the functions of the component, but it does not seem to be accessible from inside the application root.

How can I call myFunction()from the root of the application?

+16
source share
3 answers

Use an event activateto do this. Whenever we load a component into a router socket, an activation event is triggered to use the ref component and invoke the appropriate method.

Parent component

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

Template

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

Child

 works(){
    console.log("works");
  }
+27

, , . @ViewChild .

, , .

, , .

, . ,

+3

@Rahul Singh :

, ,
( ) onActivate(componentRef),
works(), .

:

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

, , , , , :

TypeError: componentRef.works

0

All Articles