Gem*_*Gem 5 angular angular-reactive-forms angular-forms angular-formbuilder angular8
我是 angular8,我在表单组内有一个表单数组,但我想检测某个输入的新更改。
ngOnInit(): void {
this.makeForm = this.fb.group({
year:['', Validators.required],
amount:['', Validators.required],
desc:['', Validators.required],
details: new FormArray([
this.det(),
])
})
det(){
return new FormGroup({
requestfor : new FormControl(''),
remarks : new FormControl('')
})}
Run Code Online (Sandbox Code Playgroud)
我必须检查 formarray 值中每个值发生变化的数据。但如果我使用,我会收到错误
this.makeForm.value.details.get('requestfor').valueChanges
Run Code Online (Sandbox Code Playgroud)
错误是
ERROR TypeError: Cannot read property 'valueChanges' of undefined
Run Code Online (Sandbox Code Playgroud)
如何获取表单数组值内的值
如何获取该值......
创建 FormGroup 时,您需要订阅 valueChanges
det(){
//use an auxiliar const
const group=new FormGroup({
requestfor : new FormControl(''),
remarks : new FormControl(''),
// file_id : new FormControl(''),
})}
//subscribe
group.get('requestForm').valueChanges.subscribe(res=>{
})
//return group
return group;
}
Run Code Online (Sandbox Code Playgroud)
您还可以拥有一个 Observables 数组,并将索引传递给您的函数 det
changesArray:Observable[]=[] //<--don't forget initialize
det(index=0){
//use an auxiliar const
const group=new FormGroup({
requestfor : new FormControl(''),
remarks : new FormControl(''),
// file_id : new FormControl(''),
})}
//fill the array
this.changesArray[index]=group.get('requestForm').valueChanges
//return group
return group;
}
Run Code Online (Sandbox Code Playgroud)
当您向 formArray 添加或删除新组时,订阅数组的 forkJoin
if (this.subscriptions)
this.subscriptions.unsubscribe();
this.subscriptions=forkJoin(changesArray)
this.subscriptions.subscribe(res=>{
})
Run Code Online (Sandbox Code Playgroud)
更新 如果我们想控制整个数组,我们可以定义一个可观察数组和一个订阅:
observables:Observable<any>[]=[]
suscription:Subscription
Run Code Online (Sandbox Code Playgroud)
我们需要创建一个函数来订阅合并最新的
controlChange()
{
if (this.suscription)
this.suscription.unsubscribe()
this.suscription=combineLatest(this.observables.map(
(o,i)=>o.pipe(startWith(this.array.controls.length>i?this.array.value[i].one:null))
)).subscribe(res=>{
console.log(res)
})
}
Run Code Online (Sandbox Code Playgroud)
当删除元素时我们调用这个函数
removeGroup(index)
{
this.array.removeAt(index);
this.observables.splice(index,1)
this.controlChange()
}
Run Code Online (Sandbox Code Playgroud)
并在函数组 Array 中添加一个新元素到 this.observables
groupArray(data:any=null)
{
data=data || {one:null,two:null}
const group=new FormGroup({
one:new FormControl(data.one),
two:new FormControl(data.two)
})
this.observables[this.array.controls.length]=group.get('one').valueChanges
this.controlChange()
return group
}
Run Code Online (Sandbox Code Playgroud)
注意:我在代码的最后一部分使用了 getter
get array() {
return this.form.get("array") as FormArray;
}
Run Code Online (Sandbox Code Playgroud)
堆栈闪电战