nco*_*hen 18 angular angular-router
我有以下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
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的孩子(使用的组件router-outlet):
@Component({
selector: 'child',
providers: [],
templateUrl: `<div>Hello World</div>`
})
export class ChildComponent {
constructor() {
}
myFunction(){
console.log('success');
}
}
Run Code Online (Sandbox Code Playgroud)
我发现我可以使用RouterOutlet来获取组件函数,但似乎无法从应用程序根目录中访问它.
如何myFunction()从应用程序根调用?
Rah*_*ngh 31
利用activate相同的事件.每当我们在路由器插座中加载一个组件时,就会发出一个激活事件,利用它来获取组件引用并调用相应的方法.
父组件
<div class="container">
<router-outlet (activate)="onActivate($event)"></router-outlet>
</div>
Run Code Online (Sandbox Code Playgroud)
模板
onActivate(componentRef){
componentRef.works();
}
Run Code Online (Sandbox Code Playgroud)
儿童比赛
works(){
console.log("works");
}
Run Code Online (Sandbox Code Playgroud)
@Rahul Singh 的一个小补充很好的答案:
确保您检查在
(留在 Rahul 的示例中) onActivate(componentRef)方法中返回了哪个组件实例,
并且仅works()在该组件确实具有这样的方法时才调用。
例子:
onActivate(componentRef){
if(componentRef instanceof ChildWithWorksMethodComponent){
componentRef.works();
return;
}
console.log("This is not the ChildWithWorksMethodComponent");
}
Run Code Online (Sandbox Code Playgroud)
否则,每次导航到一个路由时,哪个组件没有这样的方法,你的控制台日志就会充满如下错误:
错误类型错误:componentRef.works 不是函数
| 归档时间: |
|
| 查看次数: |
7425 次 |
| 最近记录: |