从父级访问路由器出口组件

时间:2017-08-16 18:29:57

标签: angular angular-router

我有以下应用根:

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

    constructor() {

    }

    callChildFunction(){
        // Call myFunction() here
    }

}

这是我的孩子(router-outlet中使用的组件):

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

    constructor() {

    }

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

}

我发现我可以使用RouterOutlet来获取组件功能,但它似乎无法从应用程序根目录中访问。

如何从应用根调用myFunction()

3 个答案:

答案 0 :(得分:27)

同样使用activate事件。 每当我们在路由器插座中加载一个组件时,就会发出一个激活事件,利用它来获取组件引用并调用相应的方法。

父组件

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

模板

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

儿童比赛

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

答案 1 :(得分:3)

路由器插座与路由有关,它与访问子组件方法无关。您必须使用@ViewChild从父级访问子组件功能。您可以找到示例here

<强>更新

如果上述情况不是一个可行的解决方案,您可以点击激活事件以获取路由器插座内实例化组件的参考。

来自文档

  

路由器插座将在实例化新组件时发出激活事件,并在销毁时发出激活事件。

因此,您可以使用这些功能并完成您的工作。您可以看到详细的答案here并且在相同的答案中附加了一个plunker

答案 2 :(得分:0)

@Rahul Singh的一个很好的补充:

确保检查,
返回了哪个组件实例。  (以拉胡尔的例子为准)onActivate(componentRef)方法,
并且仅在该组件确实具有这种方法的情况下调用works()

示例:

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

否则,每当您导航到某个路线时,哪个组件没有这种方法,您的控制台日志将充满错误,如:

  

错误TypeError:componentRef.works不是函数

相关问题