angular - Get routerLink DOM element after clicking without binding (click) event - Stack Overflow

Let's assume I have something like this in my code:<button routerLink="account" rou

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.

Share Improve this question asked Mar 23 at 18:14 Michał BMichał B 5151 gold badge5 silver badges16 bronze badges 1
  • 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
Add a comment  | 

1 Answer 1

Reset to default 1

I 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信