【发布时间】:2019-07-09 14:53:31
【问题描述】:
我正在尝试构建这个:
┌--------------------------------------------┐
| -Page 1- -Page 2- -Page 3- |
├----------┬---------------------------------┤
| Link 1 | <router-outlet></router-outlet> |
| Link 2 | |
| Link 3 | |
| | |
| | |
左侧的链接列表取决于页面。
典型的页面如下所示:
<div>
<app-component-1 appAnchor anchorTitle="Link 1"></app-component-1>
<app-component-2 appAnchor anchorTitle="Link 2"></app-component-2>
<app-component-3 appAnchor anchorTitle="Link 3"></app-component-3>
</div>
有一些指令 appAnchor 关联到 @Input() anchorTitle: string 。我想自动捕获它们并更新左侧菜单。
当我尝试通过router-outlet 查询这些元素时,问题就来了。
所以我尝试了:
@ViewChildren(AnchorDirective)
viewChildren: QueryList<AnchorDirective>;
@ContentChildren(AnchorDirective)
contentChildren: QueryList<AnchorDirective>;
ngAfterContentInit(): void {
console.log(`AppComponent[l.81] contentChildren`, this.contentChildren);
}
ngAfterViewInit(): void {
console.log(`AppComponent[l.85] viewChildren`, this.viewChildren);
}
但我总是得到一些空的QueryList:
QueryList {dirty: false, _results: Array(0), changes: EventEmitter, length: 0, last: undefined, ...}
我也试过了:
@ContentChildren(AnchorDirective, {descendants: true})
@ContentChildren(AnchorDirective, {descendants: false})
最后,我尝试在最后一刻查询元素:
<router-outlet (activate)="foo()"></router-outlet>
注意:我不希望子组件通过服务向父组件发送数据,因为它会导致一些ExpressionChangedAfterItHasBeenCheckedError 和is considered as a bad practice。我真的更喜欢直接从父组件查询链接。
编辑:这是一个stackBlitz 显示问题。如果在组件内部使用@ViewChildren,一切正常。但如果在根组件中使用@ViewChildren,则会失败。
【问题讨论】:
-
“当我尝试通过路由器插座查询这些元素时”,这是什么意思?如果您在示例中添加了一些类名,那么在答案/cmets 中会更容易引用
-
@Drenai 我正在尝试引用具有
AnchorDirective的元素(因此具有appAnchor属性的元素)。我在问题末尾添加了一个有效的 StackBlitz。 -
只是想知道这一切的最终目标是什么?尝试达到什么目标?因为这一切看起来有点……奇怪而且太复杂了。
-
伟大的 StackBlitz 演示。很好的解释问题????
-
@Dimanoid 目的是做一个自动目录。
标签: angular typescript