Let's assume I have something like this in my code:
<button routerLink="/account" routerLinkActive="active">Account</button>
Is there a way to access this element when it's clicked but without binding click event? At any stage of navigating process?
I want to create reusable component and it would be nice not having to adding some additional logic except routerLink
.
Let's assume I have something like this in my code:
<button routerLink="/account" routerLinkActive="active">Account</button>
Is there a way to access this element when it's clicked but without binding click event? At any stage of navigating process?
I want to create reusable component and it would be nice not having to adding some additional logic except routerLink
.
- How are you going to use the reusable component? Is it going to be a wrapper around button/link/etc and use ng-content? If so, you can use contentChild(RouterLink, { read: ElementRef<HTMLElement> }), and listen to any event in ngAfterContentInit. – I.Orlovsky Commented Mar 24 at 23:23
1 Answer
Reset to default 1I would use attribute directive for this.
import { Directive, ElementRef, inject } from '@angular/core';
@Directive({
selector: '[appLink]',
host: {
'(click)': 'doSomething($event)',
},
})
export class LinkDirective {
private elementRef = inject(ElementRef);
doSomething(event: PointerEvent): void {
// ...
}
}
If you want to apply this directive to every element with routerLink
, you can specify this in selector:
selector: '[routerLink]',
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744276701a4566364.html
评论列表(0条)