在Angular中,我想动态创建“添加更多字段”。
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
....
....
export class CastComponent implements OnInit {
public form: FormGroup;
public contactList: FormArray;
get contactFormGroup() {
return this.form.get('contacts') as FormArray;
}
ngOnInit() {
this.form = this.fb.group({
crew_name: [null],
crew_role: [null],
contacts: this.fb.array([this.createContact()]),
});
this.contactList = this.form.get('contacts') as FormArray;
}
...
...
}
在.html
文件中:
<form [formGroup]="form" (submit)="submit()">
<p class="mb-3"> </p>
<h3>Crew</h3>
<div class="row mb-4">
<div class="col-sm-12 col-md-6 col-lg-6">
<label class="required">Member Name</label>
<input type="text" class="form-control" >
</div>
<div class="col-sm-12 col-md-6 col-lg-5">
<label class="required">Role</label>
<!-- <input type="text" class="form-control" value="Director"> -->
<select class="form-control" type="text" >
<option value="">Select</option>
<option value="1">Director</option>
<option value="2">Music Composer</option>
<option value="3">Writer</option>
</select>
</div>
</div>
<span formArrayName="contacts">
<div class="row mb-4" *ngFor="let contact of contactFormGroup.controls; let i = index;">
<div class="col-sm-12 col-md-6 col-lg-6">
<input type="text" class="form-control" formControlName="crew_name">
</div>
<div class="col-sm-12 col-md-6 col-lg-5">
<!-- <input type="text" class="form-control" value="Writer"> -->
<select class="form-control" type="text" formControlName="crew_role">
<option value="">Select</option>
<option value="1">Director</option>
<option value="2">Music Composer</option>
<option value="3">Writer</option>
</select>
</div>
<div class="col-sm-1 col-md-1 col-lg-1"><p class="add-more mb-3"><a href="javascript:void(0)" (click)="removeContact(i)"> - remove</a></p></div>
</div>
</span>
<p class="add-more mb-3"><a href="javascript:void(0)" (click)="addContact()">+ add</a></p>
<div class="row">
<div class="col-12 text-right">
<button class="btn btn-primary" type="submit">Save & Next</button>
</div>
</div>
</form>
在控制台中,我看到以下错误:
错误错误:找不到路径为“ contacts-> crew_name”的控件
此外,提交后,联系人数组显示为空白
联系人:Array(1) 0: crew_name:空 crew_role:空
答案 0 :(得分:2)
当您位于HTML的formArrayName
指令中时,您需要使用[formGroupName]="i"
指定当前索引,就像使用包含命名属性的表单组一样。
<span formArrayName="contacts">
<div *ngFor="let contact of contactFormGroup.controls; let i = index;"
[formGroupName]="i">
<!-- the controls for the ith form group in the array -->
</div>
</span>