我正在尝试创建一个与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);
}
问题是,links
和linksWithHrefs
变量从不填充任何内容。我错过了什么? this stackblitz中的完整代码。我正在使用Angular 7。
有两个问题,一个与您的指令的实现直接相关:
RouterModule
,最重要的是调用forRoot(...)
进入你的根模块。因此,根组件模板中的锚点不限于RouterLinkWithHref
实例的实例目前,如果您基本上将您的指令重构为in this stackblitz属性,它将按预期工作。