Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

304
Views
Cannot get active element form template

I've a simple component as following where I am trying to get reference to the active element from it's template.

export class SidebarComponent {
  @ViewChildren(RouterLinkActive) linkItems: QueryList<RouterLinkActive>;

  ngAfterViewInit() {
    let activeLink = this.linkItems.find(item => item.isActive);

    console.log('Active link is');
    console.log(activeLink); //this is undefined
  }

}

And here is a simple template for above component.

<ul>
  <li>
    <a [routerLink]="['/app/link1']" routerLinkActive="active"> Link 1</a>
  </li>
  <li>
    <a [routerLink]="['/app/link2']" routerLinkActive="active"> Link 2</a>
  </li>
</ul>

The problem is I am not getting the active element from the template even though the style is applied to the element with active class. The same code worked with angular v2 but breaked in angular v4. What should I do to get the active element in angular v4?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I'd try

constructor(private router:Router) {}

...

let isLinkActive = this.linkItems.toArray()[0].isLinkActive(this.router);

let activeLink = this.linkItems.find(item => isLinkActive(item));

I assume your check just happens too early (when isActive is not yet set)

See also the code in https://github.com/angular/angular/blob/82417b3ca59aa2e5f41ee12db4cb18970b5b4f47/packages/router/src/directives/router_link_active.ts (lines 98, 108, 132)

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!