'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
Solution 1:[1]
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.
Solution 2:[2]
Maybe you should use @ViewChildren and templateRef something like that example.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | DFSFOT |
| Solution 2 | Piotr Sternik |
