Home > Software design >  Angular not grabbing elements by class name when page is loaded
Angular not grabbing elements by class name when page is loaded

Time:05-07

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 >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

CodePudding user response:

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.

CodePudding user response:

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

  • Related