简体   繁体   English

角4获取[routerLink] ViewChildren

[英]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>; 我试图建立一个@ViewChildren(RouterLink) links: QueryList<RouterLink>; . This list was always empty though. 该列表始​​终为空。

A quick experiment with @ViewChild(RouterLink) elem: RouterLink; @ViewChild(RouterLink) elem: RouterLink;快速实验@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. 我检查了以下文档: https :not(a)[routerLink] ,其中选择器实际上是:not(a)[routerLink] ,因此该实验很有意义。

Now is the question: How do I get a list of [routerLink] that are an attribute of an <a> element? 现在的问题是:如何获取作为<a>元素属性的[routerLink]列表? I couldn't find any AComponent or something suspicious. 我找不到任何AComponent或可疑的东西。

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. 可能的后备方法是,在所有元素上添加一个ID <a #myLink [routerLink]="[]"> ,但这似乎<a #myLink [routerLink]="[]"> ,因为我已经有了一个要使用的识别标准。

How can I find my list of [routerLink] s? 如何找到[routerLink]的列表?

I was looking for the same thing when i saw there was a RouterLinkWithHref . 看到有一个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. 我尝试过,实际上,(使用a和不使用a )都可以。

It's all supposition but they might have created RouterLinkWithHref to interact with existing anchor mechanism (useful for SEO). 都是假设,但他们可能已经创建了RouterLinkWithHref来与现有锚机制(对于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. 无论如何,我没有找到在单个ViewChildren中获得RouterLinkRouterLinkWithHref任何解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM