Michael Wolf Hoffman
Michael Wolf Hoffman

Reputation: 377

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

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);
        });
        */
  }
}

Upvotes: 0

Views: 230

Answers (1)

bc1105
bc1105

Reputation: 1270

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>

Upvotes: 1

Related Questions