实现效果
form表单控件的实时更新
效果如图
关键代码
validateForm: FormGroup; // 表单校验
constructor(
private fb: FormBuilder
) {
this.validateForm = this.fb.group({
});
}
// 这里有一个控件数组,包含控件的显示名称、属性名和控件类型
this.properties=[
{nameChain:'account',controlType:0,displayName:'账号'},
{nameChain:'password',controlType:1,displayName:'密码'},
];
// 先清理之前的控件
this.validateForm.clearValidators();
this.properties.forEach(property => {
// 根据新控件数组,插入控件
this.validateForm.addControl(property.nameChain, this.fb.control(null, Validators.required));
});
前端循环properties,填充控件即可
<form nz-form [formGroup]="validateForm">
<nz-form-item *ngFor="let property of properties">
<nz-form-label [nzSm]="2" [nzXs]="2" nzRequired>{{property.displayName}}</nz-form-label>
<!--输入框-->
<nz-form-control [nzSm]="4" [nzXs]="4" *ngIf="property.controlType==0">
<input nz-input [formControlName]="property.nameChain" type="text" class="form-control" name="{{property.nameChain}}" [(ngModel)]="dataObj[property.nameChain]">
</nz-form-control>
<!--密码框-->
<nz-form-control [nzSm]="4" [nzXs]="4" *ngIf="property.controlType==1">
<input nz-input type="password" [formControlName]="property.nameChain" class="form-control" name="{{property.nameChain}}" [(ngModel)]="dataObj[property.nameChain]">
</nz-form-control>
<!--下拉框-->
<nz-form-control [nzSm]="4" [nzXs]="4" *ngIf="property.controlType==2">
<nz-select [(ngModel)]="dataObj[property.nameChain]" class="form-control" name="modules" [formControlName]="property.nameChain">
<nz-option *ngFor="let city of cities" [nzValue]="city.id" [nzLabel]="city.name">
</nz-option>
</nz-select>
</nz-form-control>
</nz-form-item>
</form>
示例代码
参考资料
Angular2 form ControlGroup who hold an undefined number of Control