在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML5/ ng2里表單Input采取數(shù)據(jù)雙向綁定問題?

ng2里表單Input采取數(shù)據(jù)雙向綁定問題?

問題:
采用ngFor循環(huán)創(chuàng)建表單并給input雙向綁定,組件中如何動(dòng)態(tài)創(chuàng)建對(duì)應(yīng)的FormControl

代碼:

UI組件使用的是 ng-zorro

模板部分:

<form nz-form [nzType]="'horizontal'" [formGroup]="defaultForm">
    <div nz-f
    orm-item nz-row *ngFor="let user of authorityList; let i = index">
        <div nz-form-label nz-col [nzSpan]="4">
        </div>
        <div nz-form-control nz-col [nzSpan]="6" [nzValidateStatus]="'success'" nzHasFeedback>
            <nz-input [ngModel]="user" [nzSize]="'large'" [formControlName]="user">
            </nz-input>
        </div>
    </div>
</form>

組件部分

public defaultForm: FormGroup;
public authorityList: any;

ngOnInit() {
    this.authorityList = ['lomo', 'lomoa'];
    //需要給每個(gè)input的name創(chuàng)建FormControl, 如何動(dòng)態(tài)化?
    this.defaultForm = new FormGroup({
      lomo: new FormControl(),
      lomoa: new FormControl(),
    });
}

_submitForm() {
    console.log(this.defaultForm.value);
}

這個(gè)authorityList是動(dòng)態(tài)變化的,如何動(dòng)態(tài)給defaultForm創(chuàng)建FormControl.

或,有沒有其它更好的辦法解決動(dòng)態(tài)創(chuàng)建的表單input數(shù)據(jù)雙向綁定問題?

謝謝。

回答
編輯回答
有點(diǎn)壞

既然你的Form表單是動(dòng)態(tài)變化的,所以你就不能使用TemplateDriven Form這種方式了。
所以你應(yīng)該使用ReactiveForm。

大致的思想就是你需要有一個(gè)container component, 將需要綁定formControl的input抽出來變成childwidget, childwidget兩個(gè)輸入?yún)?shù)user和fmgrp。

 <div nz-row *ngFor="let user of authorityList; let i = index">
     <div nz-col [nzSpan]="4">
     </div>
     <div nz-col [nzSpan]="6" [nzValidateStatus]="'success'" nzHasFeedback>
         <childwidget [user]="user" [fmgrp]="defaultForm"></childwidget>
     </div>
 </div>

ngOnInit() { 
    this.defaultForm = new FormGroup({});
}

所以childwidget就變成這樣了

@Component({
    selector: 'childwidget',
    template: `
         <nz-input [formControl]="formCtrl">
         </nz-input>
    `
});

@Input() user: string;
@Input() fmgrp: FormGroup;
formCtrol: FormControl = new FormControl("");

ngOnInit() {
  if (this.fmgrp) {
     this.fmgrp.addControl(this.user, this.formControl);
  }
}

這樣無論你有多少個(gè)input,formGroup都能添加對(duì)應(yīng)額formControl。
然后你操作這個(gè)defaultForm這個(gè)變量就可以了。

2017年10月25日 07:48