我试图在我的角html
视图中获得document.getElementsByClassName('side-nav-link-ref');
元素,并且它一直返回空。我已经把它缩小到<ng-container>
,我做了一个ngfor
循环来显示数组中的所有值(它创建了一个下拉列表)。循环在适当的html
标签和类中执行并显示页面。
<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>
当我在dev-tools控制台运行document.getElementsByClassName('side-nav-link-ref');
时,我得到了所需的结果,但当我在项目中运行它时,它告诉我它没有看到任何东西。
。ts文件
@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);
}
}
结果应该
ngOnInit在组件加载时调用,但视图仍在加载中。你需要ngAfterViewInit因为你想操纵dom/view。参见Angular生命周期钩子。
你的ts文件也有错误的类名。
也许你应该使用@ViewChildren和templateRef之类的东西。