已获取Angular FormArray,如何获取其中元素的FormControl名称?
如何获取FormArray内的FormControl及其名称
首先得明确你的fines数组里的每一项类型——是单个FormControl,还是包含多控件的FormGroup?两种场景处理方式不同,下面分别说明:
场景1:FormArray元素是单个FormControl
如果你的fines直接存放独立的FormControl(比如通过this.fines.push(this.formBuilder.control(''))添加),可以遍历数组拿到每个控件,索引可作为它的标识,也可以手动给控件设置name属性:
// 遍历fines里的所有控件 this.fines.controls.forEach((control: FormControl, index: number) => { // 获取控件值 const controlValue = control.value; // 用索引作为控件的标识 console.log(`第${index}个控件值:`, controlValue); // 若要给控件设置名称,创建时可以指定 // this.fines.push(this.formBuilder.control('', { name: `fine_item_${index}` })); // 之后通过control.name获取名称 console.log(`控件名称:`, control.name); });
场景2:FormArray元素是FormGroup(更常用)
如果每个罚款项是包含多个字段的FormGroup(比如金额、原因),先给数组添加FormGroup,再遍历每个分组里的控件:
先写添加FormGroup的方法:
addFineItem(): void { const fineGroup = this.formBuilder.group({ amount: [0, Validators.required], reason: ['', Validators.required] }); this.fines.push(fineGroup); }
遍历获取分组内的控件及名称:
this.fines.controls.forEach((group: FormGroup, groupIndex: number) => { // 遍历FormGroup的所有键值对(控件名+控件实例) Object.entries(group.controls).forEach(([controlName, control]) => { console.log(`第${groupIndex}项的${controlName}控件值:`, control.value); console.log(`控件名称:`, controlName); }); });
模板中获取控件(HTML端)
如果要在模板里绑定或展示控件,写法如下:
<div [formGroup]="transactionForm"> <div formArrayName="fines"> <!-- 遍历FormArray的每个元素 --> <div *ngFor="let fineGroup of fines.controls; let i = index" [formGroupName]="i"> <input formControlName="amount" placeholder="罚款金额"> <input formControlName="reason" placeholder="罚款原因"> <!-- 直接获取控件值或状态 --> <p>当前金额: {{ fineGroup.get('amount')?.value }}</p> <p>控件名称: amount</p> </div> </div> </div>
内容的提问来源于stack exchange,提问作者jedda ler
相关产品推荐
相关产品推荐

