Answer the question
In order to leave comments, you need to log in
How to get the data of a specific element on the page?
Hello.
There is a menu
<div class="menu__item"
routerLinkActive #rla="routerLinkActive"
[routerLinkActiveOptions]="{ exact: true }"
*ngFor="let item of nav">
<a routerLink="/{{ item.link }}" [ngClass]="{'menu__link': true, 'menu__link--active': rla.isActive}">
<icon class="menu__icon" name="{{ item.icon }}"></icon>
</a>
</div>
Answer the question
In order to leave comments, you need to log in
It's also possible like this:
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);
}
}
}
<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($target){
console.log($target.getBoundingClientRect());
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question