【发布时间】:2019-11-23 12:36:39
【问题描述】:
我试图在一个角度组件中使用document.getElementsByClassName,但有时我会得到意想不到的价值。 document.getElementsByClassName 有时会给出一个值(HTML 元素),有时是undefined。
我在ngOnInit中有这段代码
window.addEventListener('load', function (){
let tabcontent = document.getElementsByClassName('tab');
console.log(tabcontent[0]); // <-----
})
我在视图模板中有这个
<div id='parent_div_2'>
<div *ngFor="let collection of collections; let i=index">
<!--targeted element -->
<div class="tab tab{{i}}" *ngIf="collection != null">
<table class="table table-borderless">
<tbody>
<tr *ngFor="let each of collection.collApps; let i = index">
<td>
<img *ngIf="imageLoaded && this.imageToShow[i]" [src]="this.imageToShow[i]"
style="width:30%;" alt="Place image title">
</td>
<td> <h4>{{each.name}}</h4></td>
<td> <form #form action="http://{{each.link}}">
<input type="submit" value="Launch" (click)="form.submit()"/>
</form> </td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
console.log 有时会输出 undefined,而有时会给出一些 HTML 元素。任何解释为什么 document.getElementsByClassName 有时会赋予 undefined 价值!!
【问题讨论】:
-
你应该使用
@ViewChildren并订阅QueryList.changes事件,如this answer和this other answer所示。 -
这一行告诉我collection != null,只有collection 不为null 时该选项卡才可用。收藏总是固定的吗?我问是因为您的代码总是在加载时执行,如果在某些情况下该集合不存在,它将返回 undefined。
-
collection始终不为空 -
@AZSH - 请展示你在
@ViewChildren技术中使用的代码和HTML标记的stackblitz。 -
@ConnorsFan 我不再使用
document.getElementsByClassName。相反,我使用了我以前不知道的@ViewChildren。
标签: javascript html angular typescript web-deployment