您可以将@ViewChild()或类似内容与路由器插座一起使用吗?如果是这样怎么办? [英] Can you use @ViewChild() or similar with a router-outlet? How if so?
问题描述
我反复遇到想要访问路由器插座另一侧而不是选择器上存在的子组件的情况:
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;
}
}
但是自然地,子级未定义,因为这是错误的方式.有正确的方法吗?
But naturally, child is undefined because this is the wrong way. Is there a right way?
我试图使用一种服务来共享数据,但随后遇到另一个问题检查后表达式已更改",我希望在没有黑客或启用产品模式的情况下进行补救.
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.
推荐答案
您可以点击激活事件以获取路由器插座内部实例化组件的引用.
You may tap into activate event to get reference of instantiated component inside the router outlet.
摘录自 RouterOutlet文档
路由器插座在任何新组件出现时都会发出激活事件 正在实例化,并在激活时将其停用 毁了.
A router outlet will emit an activate event any time a new component is being instantiated, and a deactivate event when it is being destroyed.
示例
@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!!');
}
}
这是 Plunker!
希望这会有所帮助!
这篇关于您可以将@ViewChild()或类似内容与路由器插座一起使用吗?如果是这样怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!