查询RouterLink和RouterLinkWithHref时,ContentChildren不会加载任何数据

问题描述 投票:2回答:1

我正在尝试创建一个与Structural Directive指令类似的RouterLinkActive

所以我实现了UnlessDirective示例,并添加了Angular的RouterLinkActive directive中的部分,通过ContentChildren装饰器获取子项。

// TODO(issue/24571): remove '!'.
@ContentChildren(RouterLink, { descendants: true })
links !: QueryList<RouterLink>;

// TODO(issue/24571): remove '!'.
@ContentChildren(RouterLinkWithHref, { descendants: true })
linksWithHrefs !: QueryList<RouterLinkWithHref>;

我的模板看起来像这样:

<p *appUnless="false">
    This paragraph is displayed because the condition is false.
    <a routerLink="/another-page">my link</a>
</p>

我试图访问链接:

ngAfterContentInit(): void {
    console.log("links length", this.links.length);
    console.log("linksWithHrefs length", this.linksWithHrefs.length);
}

问题是,linkslinksWithHrefs变量从不填充任何内容。我错过了什么? this stackblitz中的完整代码。我正在使用Angular 7。

angular typescript
1个回答
1
投票

有两个问题,一个与您的指令的实现直接相关:

  1. 你没有导入RouterModule,最重要的是调用forRoot(...)进入你的根模块。因此,根组件模板中的锚点不限于RouterLinkWithHref实例的实例
  2. 您的指令是结构化的事实不允许您查询内容子项。这是语言变得有点棘手的地方,所以我会做一些研究,然后我会更新我的答案。

目前,如果您基本上将您的指令重构为in this stackblitz属性,它将按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.