代码之家  ›  专栏  ›  技术社区  ›  Marcos Dimitrio Thierry Templier

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

  •  2
  • Marcos Dimitrio Thierry Templier  · 技术社区  · 7 年前

    我想创造一个 Structural Directive 其行为将类似于 RouterLinkActive 指令。

    所以我实现了 UnlessDirective 示例并添加了 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 . 我用的是角7。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jota.Toledo    7 年前

    有两个问题,一个与指令的执行直接相关:

    1. 您没有导入 RouterModule ,最重要的是 forRoot(...) ,进入根模块。因为这个原因,锚 在根组件模板中没有绑定到 RouterLinkWithHref 实例。

    2. 你的指令是结构性的 允许您查询内容子级。这就是语言 有点棘手,所以我会做些调查,更新我的答案 后来。

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

    推荐文章