Angular2 为 formGroup 设置值

Angular2 set value for formGroup

所以我有一个用于创建实体的复杂表单,我也想用它进行编辑,我正在使用新的 angular 表单 API。我完全按照从数据库中检索到的数据构建表单,因此我想将整个表单的值设置为检索到的数据这里是我想做的一个例子:

this.form = builder.group({
      b : [ "", Validators.required ],
      c : [ "", Validators.required ],
      d : [ "" ],
      e : [ [] ],
      f : [ "" ]
    });
this.form.value({b:"data",c:"data",d:"data",e:["data1","data2"],f:data});

PS:NgModel 不适用于新形式 api 我也不介意像

那样在模板中使用一种数据绑定方式
<input formControlName="d" value="[data.d]" />

可行,但在数组的情况下会很痛苦

"NgModel doesn't work with new forms api".

事实并非如此。你只需要正确使用它。如果您使用反应式形式,则应 与反应式指令 一起使用 NgModel。参见 the example in the source

/*
 * @Component({
 *      selector: "login-comp",
 *      directives: [REACTIVE_FORM_DIRECTIVES],
 *      template: `
 *        <form [formGroup]="myForm" (submit)='onLogIn()'>
 *          Login <input type='text' formControlName='login' [(ngModel)]="credentials.login">
 *          Password <input type='password' formControlName='password'
 *                          [(ngModel)]="credentials.password">
 *          <button type='submit'>Log in!</button>
 *        </form>
 *      `})
 * class LoginComp {
 *  credentials: {login:string, password:string};
 *  myForm = new FormGroup({
 *    login: new Control(this.credentials.login),
 *    password: new Control(this.credentials.password)
 *  });
 *
 *  onLogIn(): void {
 *    // this.credentials.login === "some login"
 *    // this.credentials.password === "some password"
 *  }
 * }
 */

虽然在 TODO comments 中看起来像,但它可能会被删除并替换为响应式 API。

// TODO(kara):  Replace ngModel with reactive API
@Input('ngModel') model: any;

我已经实施了一个临时解决方案,直到 angular2 支持 updateValue

 initFormGroup(form: FormGroup, data: any) {
        for(var key in form.controls) {
          console.log(key);
          if(form.controls[key] instanceof FormControl) {
            if(data[key]){
              let control = <FormControl>form.controls[key];
              this.initFormControl(control,data[key]);
            }
          } else if(form.controls[key] instanceof FormGroup) {
            if(data[key]){
              this.initFormGroup(<FormGroup>form.controls[key],data[key]);
            }
          } else if(form.controls[key] instanceof FormArray) {
            var control = <FormArray>form.controls[key];
            if(data[key])
            this.initFormArray(control, data[key]);
          }
        }
      }
      initFormArray(array: FormArray, data: Array<any>){
    if(data.length>0){
      var clone = array.controls[0];
      array.removeAt(0);
      for(var idx in data) {
        array.push(_.cloneDeep(clone));
        if(clone instanceof FormGroup)
          this.initFormGroup(<FormGroup>array.controls[idx], data[idx]);
        else if(clone instanceof FormControl)
          this.initFormControl(<FormControl>array.controls[idx], data[idx]);
        else if(clone instanceof FormArray)
          this.initFormArray(<FormArray>array.controls[idx], data[idx]);
      }
    }
  }


initFormControl(control: FormControl, value:any){
    control.updateValue(value);
  }

用法:

this.initFormGroup(this.form, {b:"data",c:"data",d:"data",e:["data1","data2"],f:data});

注意:表单和数据必须具有相同的结构,我已经使用 lodash 进行深度克隆 jQuery 其他库也可以做到

正如评论中所指出的,在提出此问题时不支持此功能。此问题已在 angular 2 rc5

中得到解决

要设置 all FormGroup 值使用,setValue:

this.myFormGroup.setValue({
  formControlName1: myValue1, 
  formControlName2: myValue2
});

要仅设置 某些 值,请使用 patchValue:

this.myFormGroup.patchValue({
  formControlName1: myValue1, 
  // formControlName2: myValue2 (can be omitted)
});

使用第二种技术,不需要提供所有值,未设置值的字段也不会受到影响。

当你的控件是FormGroup时设置值可以用这个例子

this.clientForm.controls['location'].setValue({
      latitude: position.coords.latitude,
      longitude: position.coords.longitude
    });

是的,您可以使用 setValue 为 edit/update 目的设置值。

this.personalform.setValue({
      name: items.name,
      address: {
        city: items.address.city,
        country: items.address.country
      }
    });

您可以参考 http://musttoknow.com/use-angular-reactive-form-addinsert-update-data-using-setvalue-setpatch/ 以了解如何使用 setValue 为 add/edit 功能使用 Reactive 表单。它节省了我的时间

可以使用form.get获取具体的控制对象,使用setValue

this.form.get(<formControlName>).setValue(<newValue>);