Or Shalmayev
Or Shalmayev

Reputation: 315

Angular get access to value of a directive in directive

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

Upvotes: 0

Views: 309

Answers (2)

paranaaan
paranaaan

Reputation: 1735

You can use Input to receive any attribute from template.

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

    ....
}

Upvotes: 1

akotech
akotech

Reputation: 2274

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

Upvotes: 1

Related Questions