在Angular中,使用ViewChildren
获取元素或组件时,可能无法获取已更改的响应式表单值。这是因为ViewChildren
返回的是QueryList
,而QueryList
是一个可观察对象,并且只会在组件初始化时或在ngOnChanges
生命周期钩子中发出一次。
要解决这个问题,可以使用rxjs
中的valueChanges
方法来订阅响应式表单的值更改。
以下是一个示例代码,演示如何使用ViewChildren
和valueChanges
来获取已更改的响应式表单值:
import { Component, QueryList, ViewChildren, AfterViewInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { debounceTime } from 'rxjs/operators';
@Component({
selector: 'app-example',
template: `
`
})
export class ExampleComponent implements AfterViewInit {
myForm: FormGroup;
@ViewChildren('input') inputs: QueryList;
constructor() {
this.myForm = new FormGroup({
input1: new FormControl(''),
input2: new FormControl('')
});
}
ngAfterViewInit() {
this.inputs.changes.pipe(debounceTime(300)).subscribe(() => {
this.getFormValues();
});
}
getFormValues() {
console.log(this.myForm.value);
}
}
在上面的代码中,我们首先创建了一个包含两个输入字段的响应式表单。然后,我们使用ViewChildren
来获取这两个输入字段,并在ngAfterViewInit
钩子中订阅QueryList
的更改。我们使用debounceTime
运算符来延迟300毫秒,以便在值更改后获取表单的最新值。最后,我们在getFormValues
方法中打印表单的值。
通过这种方式,我们可以确保在每次表单值更改时都能及时获取到最新的值。