无法使用角创建动态反应形式 [英] unable to create the dynamic reactive forms using angular
本文介绍了无法使用角创建动态反应形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用角度创建动态反应形式,但是我可以将其循环显示,但它显示的是确切的方式
i am trying to create the dynamic reactive form using angular i am able to loop it but it is displaying the exact way
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div *ngFor="let dat of formData;let index = index;">
<label for="{{dat.name}}">{{dat.name }}</label>
<input type="text" id="{{dat.id}}" [formControlName]="dat.name" />
</div>
</form>
<button type="button"><button>
.ts
registerForm: FormGroup;
submitted = false;
formData = [{ id: 'firstName', name: 'firstName' },
{ id: 'lastName', name: 'lastName' },
{ id: 'address', name: 'address' },
{ id: 'emailid', name: 'emailid' }
]
constructor(private formBuilder: FormBuilder) {
this.registerForm = this.formBuilder.group({
formData: []
});
}
onSubmit(){
console.log(this.registerForm.value);
}
包括验证
下面是我的stackblitz网址
below is my stackblitz url
https://stackblitz.com/edit/angular-awguej
推荐答案
您可以为此使用this.formBuilder.array
.
Stackblitz
component.html
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div formArrayName="formData">
<div *ngFor="let dat of registerForm.get('formData').controls;let index = index;" [formGroupName]="index">
<label>{{dat.get('name').value }}</label>
<input type="text" formControlName="name" />
</div>
<button type="submit">Submit</button>
</div>
</form>
<button type="button" (click)="addNew()">Add</button>
component.ts
registerForm: FormGroup;
submitted = false;
constructor(private formBuilder: FormBuilder) {
this.registerForm = this.formBuilder.group({
formData: this.formBuilder.array([this.createNewGroup()])
});
}
createNewGroup() {
return this.formBuilder.group({
id: ['id'],
name: ['name']
})
}
addNew(){
let formArr=this.registerForm.get('formData') as FormArray;
formArr.push(this.createNewGroup());
}
onSubmit(){
console.log(this.registerForm.value);
}
这篇关于无法使用角创建动态反应形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文