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

110
Visualizações
Angular not grabbing elements by class name when page is loaded

I am trying to get the document.getElementsByClassName('side-nav-link-ref'); elements in my angular html view and It keeps returning empty. I’ve narrowed it down to the <ng-container> that I have doing a ngfor loop to display all the values in the array (Its creating a dropdown list). The loop is executing and displaying the page in the proper html tags and classes.

  <div #testElm>
    <ng-container *ngFor="let item of list">
       <p>This is a test 1</p>
       <p class="test-link">This is a test 2</p>
       <p>This is a test 3</p>
    </ng-container>
  </div>

When I run document.getElementsByClassName('side-nav-link-ref'); in the dev-tools console I get the desired results but when I run it in my project it shows me that It doesn’t see anything.

.ts file

@ViewChild('testElm') testElm!: ElementRef;

 list: any [] = [1];
 
  ngOnInit(): void {   
    this._testFunction(); 
  }
 
  _testFunction() { 
    const test: any = document.getElementsByClassName('test-link');
    for (let index = 0; index < test.length; index++) {      
      console.log('sTest: ' + test.length); 
      
    }
  }

The result should

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

ngOnInit is called when the component is loaded, but the view is still loading. You need ngAfterViewInit because you're trying to manipulate the dom/view. See Angular lifecycle hooks.

Also your ts file has the wrong classname.

about 4 years ago · Juan Pablo Isaza Relatório

0

Maybe you should use @ViewChildren and templateRef something like that example.

about 4 years ago · Juan Pablo Isaza 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