在 ngIf (Angular 5) 之后获取父元素的子元素
Get children of parent element after ngIf (Angular 5)
我正在尝试获取仅在布尔值变为真后才存在的所有 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
总是打印一个空数组。但是,如果我在将布尔值设置为 true 后在浏览器控制台中手动键入查询选择器,那么它 returns 两个 input
元素。
我做错了什么?怎么在输入元素加入到DOM后就得不到输入元素了?如有任何帮助,我们将不胜感激!
不要以这种方式访问 DOM。 Angular 方式是使用 ElementRef.
也看看那些解释如何使用的线程:
private contentPlaceholder: ElementRef;
@ViewChild('contentPlaceholder') set content(content: ElementRef) {
this.contentPlaceholder = content;
}
<div #contentPlaceholder *ngIf="isTestChecked">
<input type="number">
<input type="text">
</div>
Angular 异步更新 DOM,因此您无法在同一事件循环中访问更新后的 DOM 元素。如果您确实需要直接操作 DOM,请尝试在查询选择之前添加超时。
this.isTestChecked = event.checked;
setTimeout(() => {
if (this.isTestChecked === true) {
const children = document.querySelectorAll('.form-area input');
console.log(children);
}
})
我正在尝试获取仅在布尔值变为真后才存在的所有 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
总是打印一个空数组。但是,如果我在将布尔值设置为 true 后在浏览器控制台中手动键入查询选择器,那么它 returns 两个 input
元素。
我做错了什么?怎么在输入元素加入到DOM后就得不到输入元素了?如有任何帮助,我们将不胜感激!
不要以这种方式访问 DOM。 Angular 方式是使用 ElementRef.
也看看那些解释如何使用的线程:
private contentPlaceholder: ElementRef;
@ViewChild('contentPlaceholder') set content(content: ElementRef) {
this.contentPlaceholder = content;
}
<div #contentPlaceholder *ngIf="isTestChecked">
<input type="number">
<input type="text">
</div>
Angular 异步更新 DOM,因此您无法在同一事件循环中访问更新后的 DOM 元素。如果您确实需要直接操作 DOM,请尝试在查询选择之前添加超时。
this.isTestChecked = event.checked;
setTimeout(() => {
if (this.isTestChecked === true) {
const children = document.querySelectorAll('.form-area input');
console.log(children);
}
})