问题描述
我反复遇到这样一种情况:我想访问位于路由器插座另一侧的子组件而不是选择器:
I repeatedly run into a situation where I'd like to access a child component existing on the other side of a router outlet rather than a selector:
Like:
<router-outlet></router-outlet>
NOT:
<selector-name></selector-name>
据我所知,这与 ViewChild 功能冲突,但似乎我的组件应该能够像查看选择器标签中的内容一样轻松地查看路由器插座中的内容并与之交互.
This conflicts with the ViewChild functionality as I know it, yet it seems like my component should be able to see and interact with what's inside that router-outlet just as easily as with what's inside a selector-tag.
例如我试过这个:
export class RequestItemCatsComp {
@ViewChild('child') child: RequestItemsComp;
***etc...***
ngAfterViewInit() {
if (this.child) // Always child is undefined
this.groupId = this.child.groupId;
}
}
但很自然地,child 是未定义的,因为这是错误的方式.有正确的方法吗?
But naturally, child is undefined because this is the wrong way. Is there a right way?
我正在尝试使用一项服务来共享数据,但随后遇到了另一个问题表达式在检查后发生了变化",我希望在不进行黑客攻击或启用 prod 模式的情况下解决该问题.
I'm trying to use a service to share the data but then run into another problem "expression has changed after it was checked" which I'm hoping to remedy without a hack or enabling prod mode.
推荐答案
您可以点击 activate 事件来获取路由器插座内实例化组件的引用.
You may tap into activate event to get reference of instantiated component inside the router outlet.
只要有新组件,路由器插座就会发出激活事件正在被实例化,并且在它被实例化时一个停用事件毁了.
示例
@Component({
selector: 'my-app',
template: `<h3 class="title">Basic Angular 2</h3>
<router-outlet (activate)="onActivate($event)" ></router-outlet>
`
})
export class AppComponent {
constructor(){}
onActivate(componentRef){
componentRef.sayhello();
}
}
@Component({
selector: 'my-app',
template: `<h3 class="title">Dashboard</h3>
`
})
export class DashboardComponent {
constructor(){}
sayhello(){
console.log('hello!!');
}
}
希望这有帮助!!
这篇关于你可以在路由器插座上使用@ViewChild() 或类似的东西吗?如果是这样怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!