【发布时间】:2022-01-06 17:47:16
【问题描述】:
如果 FormArray 在子组件中而我的主窗体在父组件中,我如何通过 FormArray 获取值(以反应方式)。我使用 FormGroups 的 FormGroupDirective 解决了这个问题,但这在 FormArrays 中不起作用(或者我不知道如何这是工作 :) )。我的目标是当我在输入中输入内容时,FormArray(product array) 中的内容是什么。它立即显示在我的主表单对象中。 这是一个 StackBlitz 链接 stackblitz
应用组件:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
constructor(private formBuilder: FormBuilder) {}
form: FormGroup;
ngOnInit(): void {
this.form = this.formBuilder.group({
name: [''],
sex: [''],
infos: this.formBuilder.group({}),
comments: this.formBuilder.array([]),
});
}
}
产品组件:
import { Component, OnInit } from '@angular/core';
import {
FormArray,
FormControl,
FormGroup,
FormGroupDirective,
} from '@angular/forms';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
})
export class ProductComponent implements OnInit {
constructor(private formDirective: FormGroupDirective) {}
productFormGroup: FormGroup;
productForm: FormArray;
ngOnInit(): void {
this.handleFormGroup();
this.productForm = this.formDirective.control.get('products') as FormArray;
}
handleFormGroup() {
this.productFormGroup = new FormGroup({
name: new FormControl(''),
quantity: new FormControl(null),
amountUnit: new FormControl(''),
});
}
}
产品html
<form class="myform" [formGroup]="productFormGroup">
<mat-form-field >
<mat-label>name</mat-label>
<input matInput formControlName="name" />
</mat-form-field>
<mat-form-field >
<mat-label>qua</mat-label>
<input matInput formControlName="quantity" />
</mat-form-field>
<mat-form-field >
<mat-label>amount</mat-label>
<input matInput formControlName="amountUnit" />
</mat-form-field>
</form>
【问题讨论】:
标签: angular angular-reactive-forms formarray formgroups