angularelementref

Angular get ElementRef of of the routerLinkActive


As in the title I need to get the ElementRef of the routerLinkActive in order to understand where I need to place an "ink Bar" (e.g. Material Design Tab) in the right position.

here I there is my sideNav menu

  <mat-sidenav fxLayout='column' 
   fxLayoutAlign='start center'#sidenav 
   mode="over" [(opened)]="opened" position="end" 
   class="nav-sidenav">

        <!-- Here the Navigation -->
        <div  class="nav-sidenav-container" fxFlex='1 1 100%'>

          <div class="ink-bar"></div> <!-- I NEED TO MOVE THIS -->
          <ul class="nav">

            <li *ngFor="let menuItem of menuItems" 
             routerLinkActive="active" class="{{menuItem.class}}">
              <a [routerLink]="[menuItem.path]">
                <i class="nav-icon-container">
                  <mat-icon>{{menuItem.icon}}</mat-icon>
                </i>
                <p>{{menuItem.title}}</p>
              </a>
            </li>

          </ul>
        </div>
      </mat-sidenav>

the first "li" element is at 180px the offset between the elements is 60px. But i need to know which is the active element at the beginning (e.g. if user paste the URL in the browser), there is a way to get the ElementRef of the activeLink


Solution

  • You can find the ElementRef by using ViewChildren and querying for RouterLinkActive directive, with read: ElementRef option.

    We delay the execution of findActiveLink method in a setTimeout, to give the RouterLinkActive time to update the view with appropriate CSS class.

    import { Component, ViewChildren, ElementRef, QueryList } from '@angular/core';
    import { RouterLinkActive } from '@angular/router';
    
    @Component({
      selector: 'my-app',
      template: `
      <a [routerLinkActive]="activeClass" routerLink="/">Hello</a>
      <a [routerLinkActive]="activeClass" routerLink="/hello">Hello</a>
      <a [routerLinkActive]="activeClass" routerLink="/world">Hello</a>
      <router-outlet></router-outlet>
      `,
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      activeClass = 'active';
    
      @ViewChildren(RouterLinkActive, { read: ElementRef })
      linkRefs: QueryList<ElementRef>
    
      constructor() { }
    
      ngAfterViewInit() {
        setTimeout(() => {
          const activeEl = this.findActiveLink();
          console.log(activeEl);
        }, 0);
      }
    
      findActiveLink = (): ElementRef | undefined => {
        return this.linkRefs.toArray()
          .find(e => e.nativeElement.classList.contains(this.activeClass))
      }
    }
    

    Live demo