您好,我正在使用 Angular 反应式表单,我使用 FormArray 动态添加表单控件。我正在使用 ngModel 指令将用户输入的数据存储在 components 变量中。但它没有将其存储在 components 变量中。我的代码是:
<form [formGroup]="reviewForm" (ngSubmit)="onSubmit()">
<div class="example-label">
<span class='block'>
<span *ngIf="selectedForm">
<h2 class="example-heading">{{displayForm}} </h2>
</span>
<div formArrayName="controlArray">
<div *ngFor="let control of reviewForm.get('controlArray').controls; let i = index">
<table>
<tr>
<td> <span *ngIf="control.value.controlType == 'text'">
<md-form-field class="example-full-width">
<input mdInput type="text" placeholder="{{control.value.placeholder}}"
([ngModel])="control.value.value" > <!--user entered data is not storing in control.value.value -->
</md-form-field>
</span></td>
</tr>
</table>
</div>
<button md-raised-button color="primary" type="submit" [disabled]="!reviewForm.valid">Submit</button>
</div>
</span>
</div>
</form>
这是组件类代码:
export class FormListComponent {
formsDb: FormData[];
selectedForm: FormData;
displayForm: String;
test: String;
reviewForm = new FormGroup({
'controlArray': new FormArray([])
});
constructor(public formService: FormService, public authGuardService: AuthGuardService) {
console.log('form-list is logged in 0528', this.authGuardService.authService.isLoggedIn);
}
ngOnInit() {
this.reviewForm = new FormGroup({
'controlArray': new FormArray([
])
});
this.showDefaultForm();
}
addForm() {
this.displayForm = this.selectedForm.formName;
this.reviewForm.setControl('controlArray', new FormArray([])); //to reset FormArray
console.log('selected form 0528', this.selectedForm);
for (let control of this.selectedForm.controlsArr) {
const myControl: Control = new Control(control.controlType, control.label, control.required,
control.placeholder, control.options);
var controlArg: FormControl;
if (control.required)
controlArg = new FormControl(myControl, Validators.required);
else
controlArg = new FormControl(myControl);
(<FormArray>this.reviewForm.get('controlArray')).push(controlArg);
}
}
onSubmit() {
console.log('submitted form 0528', this.reviewForm);
}
}
这是我的 Control 类,我将它的对象传递给 FormControl 构造函数:
export class Control{
constructor(public controlType?:string, public label?:string, public required?:boolean ,public placeholder?:string,
public options?:string[], public value?:string){ }
}
为了检查用户输入的数据是否存储在组件的变量中,我记录了我的 FormGroup 变量,即在这种情况下的 reviewForm。没有数据保存在其中。请帮忙,谢谢