Home > OS >  How can access to routerLink value via custom directive?
How can access to routerLink value via custom directive?

Time:10-08

How can I create a custom directive(e.g. appCheckPermission ) to check if user can view a link or button base on routerLink that applied to that element.

<button [routerLink]="['/users/edit', userId]" appCheckPermission ></button>

p.s: there is a property that save routerlink value

nativeElement.attributes["ng-reflect-router-link"].value

but can not be access via custom directive.

CodePudding user response:

You can access the router link in the directive in ngOnChanges Lifecycle hook.

import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';

@Directive({
  selector: '[appCheckPermission]',
})
export class CheckPermissionDirective implements OnChanges {
  @Input() routerLink: any;

  constructor() {}

  ngOnChanges(changes: SimpleChanges) {
    if (changes && changes.routerLink) {
      console.log(changes.routerLink.currentValue);
    }
  }
}

CodePudding user response:

It should be accessible as an Input property and inside the lifecycle hooks

@Directive({ selector: '[appCheckPermission]' })
export class AppCheckPermissionDirective implements OnInit {
  @Input() routerLink: any;

  ngOnInit(): void {
    console.log(this.routerLink);
  }

  ...
}
  • Related