Search code examples
angularrouterlinkviewchild

Angular 4 get [routerLink] ViewChildren


I'm trying to get a list of all links in my current component, with a template looking something along the lines of this:

<div *ngFor="let link of links">
  <a [routerLink]="[link.url]">{{ link.label }}</a>
</div>

I tried to set up an @ViewChildren(RouterLink) links: QueryList<RouterLink>;. This list was always empty though.

A quick experiment with @ViewChild(RouterLink) elem: RouterLink;:

<div [routerLink]="[]">Bla</div>

returns a value, while

<a [routerLink]="[]">Bla</a>

does not.

I checked in the documentation: https://angular.io/api/router/RouterLink, where the selector is actually given as :not(a)[routerLink], so the experiment makes sense.

Now is the question: How do I get a list of [routerLink] that are an attribute of an <a> element? I couldn't find any AComponent or something suspicious.

A possible fallback would be, to add an ID on all elements <a #myLink [routerLink]="[]">, but that seems kind of weird, since I already have an identifying criterion I'd like to use.

How can I find my list of [routerLink]s?


Solution

  • I was looking for the same thing when i saw there was a RouterLinkWithHref. I didn't have time to try it, but I suppose it can help you.

    If I have the time latter, I'll try it and edit my answer.

    [EDIT]

    I tried and indeed, both (with and without a a) works.

    It's all supposition but they might have created RouterLinkWithHref to interact with existing anchor mechanism (useful for SEO).

    Then making the directive for none anchor tags seems logical (overlaping a component selector and a directive selector doesn't feel right).

    Anyway, I didn't found any solution to get RouterLink and RouterLinkWithHref in a single ViewChildren.