Можно еще так:
import { Directive, Output, ElementRef, EventEmitter, ContentChildren } from '@angular/core';
import { NavigationEnd, Router, RouterLinkActive, RouterLinkWithHref } from '@angular/router';
import { Subscription } from 'rxjs';
@Directive({
selector: '[routerLink]'
})
export class ActiveRouteDirective {
@ContentChildren(RouterLinkWithHref, { descendants: true }) linksWithHrefs;
@Output('isActiveRouteEmitter') isActiveEmitter: EventEmitter<any> = new EventEmitter<any>();
private subscription: Subscription;
constructor(
private router: Router,
private element: ElementRef
) {
this.router = router;
this.element = element;
this.subscription = router.events.subscribe(s => {
if (s instanceof NavigationEnd) {
this.update();
}
});
}
ngAfterContentInit() {
this.linksWithHrefs.changes.subscribe(() => this.update());
this.update();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
update() {
if (!this.linksWithHrefs || !this.router.navigated) return;
const isActive = this.linksWithHrefs.some(link => this.router.isActive(link.urlTree, true));
if (isActive) {
this.isActiveEmitter.emit(this.element.nativeElement);
}
}
}
HTML код<div class="menu__item" #rla="routerLinkActive" routerLinkActive="menu__item--active" [routerLinkActiveOptions]="{ exact: true }" *ngFor="let item of menu">
<a (isActiveRouteEmitter)="getParams($event)" routerLink="/{{ item.link }}" [ngClass]="{'menu__link': true, 'menu__link--active': rla.isActive}">
{{ item.name }}
</a>
</div>
Добавляем метод getParams в компонентgetParams($target){
console.log($target.getBoundingClientRect());
}
Ссылка с рабочим примером