B
B
Bowen2018-08-08 13:32:07
Angular
Bowen, 2018-08-08 13:32:07

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>

How can I get the width, height, padding, etc. of an active link?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
0
0xD34F, 2018-08-08
@Bowen

The element itself - using ViewChild . Well, then - getComputedStyle .

B
Bowen, 2018-08-09
@Bowen

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

Link with working example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question