0

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

Here is my navbar html with the 'authorize' attribute in the top level of the list.

  <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(). So far I have been unable to retrieve these values from 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);
        });
        */
  }
}
  • The `[authorize]` seems to only be on the top level `
      ` which has no `href` attribute. Is there a reason why your aren't working with the children of `this.el` to traverse down to the `` tags?
    – Daniel W Strimpel Apr 12 '18 at 17:24
  • I have tried that like this, but get null for each link `let items = this.el.children; for (const i of items) { let link:HTMLElement = i.children[0]; console.log(link.getAttribute('href')); // this.routerGuard.permissionApproved(link); }` – Michael Wolf Hoffman Apr 12 '18 at 17:34

1 Answers1

1

Ugly example running in 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>
bc1105
  • 1,270
  • 8
  • 8
  • Here is a Plunker that I was putting together showing this before this was posted. Hope it helps: https://plnkr.co/edit/mk9HAavGNoejDg9jwBcm?p=preview – Daniel W Strimpel Apr 12 '18 at 17:56