简体   繁体   English

创建角度指令时,如何从ElementRef获取列表项的属性值? 角度5

[英]Creating angular directive, how do I get list item's attribute values from ElementRef? Angular 5

I have a typical navbar with a list of links. 我有一个带有链接列表的典型导航栏。

I am trying to clean the HTML for the navbar by creating a simple angular directive ('authorize') as shown in the HTML snippet below, but to do this I need my Directive to be able to receive the value of the [routerLink] attribute of each li item in the list 我正在尝试通过创建一个简单的角度指令(“ authorize”)来清理导航栏的HTML,如下面的HTML代码段所示,但是为此,我需要我的指令能够接收[routerLink]属性的值列表中每个li项目的数量

Here is my navbar html with the 'authorize' attribute in the top level of the list. 这是我的导航栏html,在列表的顶层具有'authorize'属性。

  <ul class="nav navbar-nav" authorize>
    <li [routerLinkActive]="['active']">
      <a [routerLink]="['/dashboard']" auth>Dashboard</a>
    </li>
    <li [routerLinkActive]="['active']">
      <a [routerLink]="['/research']" auth>Research</a>
    </li>
    <li [routerLinkActive]="['active']">
      <a [routerLink]="['/profile']" auth>Profile</a>
    </li>
    <li [routerLinkActive]="['active']">
      <a [routerLink]="['/users']" auth>Users</a>
    </li>
    <li [routerLinkActive]="['active']">
      <a [routerLink]="['/todo']" auth>Todo-List-App</a>
    </li>
  </ul>

I want my directive to be able to read each routerLink value and pass that value to this.routerGuard.permissionApproved(). 我希望我的指令能够读取每个routerLink值,并将该值传递给this.routerGuard.permissionApproved()。 So far I have been unable to retrieve these values from ElementRef. 到目前为止,我一直无法从ElementRef检索这些值。

 @Directive({ selector: '[authorize]' }) export class AuthorizationDirective implements OnInit { private el; constructor(private ref: ElementRef, private routerGuard: RouteGuard, private renderer: Renderer) { this.el = this.ref.nativeElement; } ngOnInit() { /* Is there away to get a list of the [routerLink] values here? let links = this.el.getAttribute('href') <- this returns null I want to iterate through a list of routerLink values and call a method in my RouteGuard class. links.forEach(link=>{ this.routerGuard.permissionApproved(link); }); */ } } 

Ugly example running in ngOnInit ngOnInit运行的丑陋示例

Array.from(this.el.children).forEach((li: Element) => {
  const link = li.firstElementChild.getAttribute('routerLink');
  if (link) {
    this.routerGuard.permissionApproved(link);
  }
});

Change your link template to not bind (router will still work): 将您的链接模板更改为绑定(路由器仍然可以使用):

<li [routerLinkActive]="['active']">
  <a routerLink="/dashboard" auth>Dashboard</a>
</li>

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

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