FormArray 值变为空错误:找不到名称为“0”的控件
Posted
技术标签:
【中文标题】FormArray 值变为空错误:找不到名称为“0”的控件【英文标题】:FormArray values getting null Error: Cannot find control with name '0' 【发布时间】:2021-12-04 02:32:54 【问题描述】:我在提交表单时无法获取 FormArray 字段值。我在表单数组字段中得到空值。
每当我点击 addHobbies 按钮时,我都会收到错误消息:找不到名称为“0”的控件
signupForm.component.html
<div class="container">
<form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
<div class="row mb-3">
<div class="form-group col-6">
<label>Email</label>
<input type="email" formControlName="email" class="form-control">
<span class="help-block">Email Required</span>
</div>
</div>
<div FormArrayName="hobbies">
<div class="row mb-3">
<div class="form-group col">
<button type="button" class="btn btn-primary" (click)="addHobbies()">Add Hobbies</button>
</div>
</div>
<div class="row mb-3">
<div class="form-group col" *ngFor="let hobby of hobbyControls.controls; let i=index">
i
<input type="text" class="form-control" [formControlName]="i">
</div>
</div>
</div>
<div class="mb-5">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-danger">Reset</button>
</div>
</form>
</div>
signupform.component.ts
export class ReactiveformsComponent implements OnInit
signupForm : FormGroup;
constructor(private fb: FormBuilder)
ngOnInit(): void
this.signupForm = this.fb.group(
'email': [''],
'hobbies': this.fb.array([])
)
addHobbies()
//const hobbyControl = this FormControl('');
(<FormArray>this.signupForm.get('hobbies')).push(this.fb.control(''));
get hobbyControls()
return this.signupForm.get('hobbies') as FormArray;
onSubmit()
console.log(this.signupForm.value);
输出
"电子邮件":"john@gmail.com","爱好":["",""]
【问题讨论】:
【参考方案1】:像这样试试,而不是我在这里使用爱好
<div class="row mb-3">
<div class="form-group col" *ngFor="let hobby of hobbyControls.controls; let i=index">
i
<input type="text" class="form-control" [formControlName]="hobby">
</div>
</div>
【讨论】:
【参考方案2】:FormArrayName
存在拼写错误。
<div FormArrayName="hobbies">
...
</div>
解决方案
将其更改为 formArrayName
以便指令生效。
<div formArrayName="hobbies">
...
</div>
Sample Solution on StackBlitz
参考文献
Angular Form Array
【讨论】:
以上是关于FormArray 值变为空错误:找不到名称为“0”的控件的主要内容,如果未能解决你的问题,请参考以下文章
[Register-PSRepository在对象上找不到值引发错误
Angular 2在formArrays上找不到具有未指定名称属性的控件