Home > front end >  Angular get access to value of a directive in directive
Angular get access to value of a directive in directive

Time:07-26

I want to create a structural directive that queries all anchors that has "routerLink" directive in the app and and access the value of the routerLink.

I tried to implement it with this way but without success:


@Directive({
    selector: '[appShowByRole], a[routerLink]'
})
export class ShowByRoleDirective implements OnInit{

    constructor(
        private readonly elmRef: ElementRef,
        @Optional() @Inject(forwardRef(() => RouterLink)) private routerLink: RouterLink,
    ) {
    }

    ngOnInit(): void {
        if (this.routerLink) {
            debugger;
        }
    }
}

CodePudding user response:

You can use Input to receive any attribute from template.

@Directive({
    selector: '[appShowByRole], a[routerLink]'
})
export class ShowByRoleDirective implements OnInit {
    @Input('routerLink') link: any;

    ....
}

CodePudding user response:

For a tags the routerLink directive class name is RouterLinkWithHref

Here you have both directives decorators extracted from the source code

RouterLinkWithHref

@Directive({
  selector: 'a[routerLink],area[routerLink]', 
  standalone: true}
)
export class RouterLinkWithHref implements OnChanges, OnDestroy {
...

RouterLink

@Directive({
  selector: ':not(a):not(area)[routerLink]',
  standalone: true,
})
export class RouterLink implements OnChanges {
...

I don't know exactly whats the aim of your directive, but you don't need to include the routerlink in you directive's selector to get the ref. Neither should you need to use forwardRef.

cheers

  • Related