1

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.

  • nativeElement.attributes["ng-reflect-router-link"].value also accessible inside life cycle hooks and I can use it :D –  Oct 07 '21 at 19:28

2 Answers2

1

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

  ...
}
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
  • Thank you for quick response. but It does not work check it [link](https://stackblitz.com/edit/angular-ivy-1iqctm?devtoolsheight=33&file=src/app/check-permission.directive.ts) –  Oct 07 '21 at 17:49
  • @user3910994 you need to access it inside the init lifecycle hook, it might not be available in constructor. Updated the snippet for your reference accordingly. – Shreevardhan Oct 07 '21 at 18:15
  • thank you. it's work –  Oct 07 '21 at 19:16
0

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

Lukasz Gawrys
  • 1,234
  • 2
  • 8