Angular 加载页面时未通过 class 名称抓取元素
Angular not grabbing elements by class name when page is loaded
我试图在我的 angular 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>
当我在开发工具控制台中 运行 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);
}
}
结果应该
也许你应该使用 @ViewChildren 和 templateRef 之类的东西 example。
ngOnInit 在加载组件时调用,但视图仍在加载。您需要 ngAfterViewInit,因为您正试图操纵 dom/view。参见 Angular lifecycle hooks。
另外你的ts文件有错误的类名。
我试图在我的 angular 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>
当我在开发工具控制台中 运行 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);
}
}
结果应该
也许你应该使用 @ViewChildren 和 templateRef 之类的东西 example。
ngOnInit 在加载组件时调用,但视图仍在加载。您需要 ngAfterViewInit,因为您正试图操纵 dom/view。参见 Angular lifecycle hooks。
另外你的ts文件有错误的类名。