我试图获取仅在 bool 值变为 true 后才存在的所有 input
元素。因此 div
包裹在 *ngIf
周围。我尝试使用纯 JavaScript 抓取元素,但它始终返回空。这是我的代码:
test.component.html
<mat-checkbox (change)="toggleTest($event)">
Test check box
</mat-checkbox>
<div class="form-area" *ngIf="isTestChecked">
<input type="number">
<input type="text">
</div>
test.component.ts
isTestChecked = false;
toggleTest(event: any) {
this.isTestChecked = event.checked;
if (this.isTestChecked === true) {
const children = document.querySelectorAll('.form-area input');
console.log(children);
}
}
因此,console.log
始终打印一个空数组。但是,如果我在将 bool 值设置为 true 后在浏览器控制台中手动键入查询选择器,则会返回两个 input
元素。
我做错了什么?为什么输入元素添加到 DOM 后无法获取它们?任何帮助将不胜感激!
最佳答案
不要以这种方式访问 DOM。 Angular 的方式是使用 ElementRef .
也请查看那些解释如何使用的线程: Angular 2 @ViewChild in *ngIf
private contentPlaceholder: ElementRef;
@ViewChild('contentPlaceholder') set content(content: ElementRef) {
this.contentPlaceholder = content;
}
<div #contentPlaceholder *ngIf="isTestChecked">
<input type="number">
<input type="text">
</div>
关于javascript - 在 ngIf 之后获取父元素的子元素(Angular 5),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50743396/