form表單控件的實時更新
效果如圖
html
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>
示例代碼git
Angular2 form ControlGroup who hold an undefined number of Controlgithub