Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

306
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda