ContentChildren won't load any data when querying RouterLink and RouterLinkWithHref

Viewed 242

I'm trying to create a Structural Directive that will behave similarly to the RouterLinkActive directive.

So I implemented the UnlessDirective example and added the parts from the Angular's RouterLinkActive directive where it obtains the children through the ContentChildren decorator.

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

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

My template looks like this:

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

And I tried to access the links with:

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

The problem is, the links and linksWithHrefs variables are never filled with any contents. What am I missing? Full code in this stackblitz. I'm using Angular 7.

1 Answers

There are 2 issues, one directly related to the implementation of your directive:

  1. You arent importing RouterModule, and most importantly calling forRoot(...), into your root module. For that reason, the anchor in your root component template is not bounded to an instance of RouterLinkWithHref instance.`

  2. The fact that your directive is structural does not allow you to query for content childs. Here is where the language gets kinda tricky, so Ill do some research and Ill update my answer later.

For the moment, if you basically refactor your directive to simply by an attribute one as in this stackblitz, it will work as expected.

Related