Angular2:使用模型驱动的表单添加并提交新的formGroup名称和值

时间:2016-08-11 12:19:35

标签: forms angular angular2-forms

通过输入字段添加到FormArray

要通过表单输入将值添加到现有数组,我可以使用(单击)=" addAddress()"在html中,在component.ts中定义了addAddress,以AppComponent的形式更新数组中的值:

ngOnInit() {
        this.myForm = this._fb.group({
            name: ['', [Validators.required, Validators.minLength(5)]],
            addresses: this._fb.array([
                this.initAddress(),
            ])
        });
    }

    initAddress() {
        return this._fb.group({
            street: ['', Validators.required],
            postcode: ['']
        });
    }

    addAddress() {
        const control = <FormArray>this.myForm.controls['addresses'];
        control.push(this.initAddress());
    }

回到html ngFor用于在每次添加&#39;时添加一组输入字段。单击按钮&#34;:

<div formArrayName="addresses">
          <div *ngFor="let address of myForm.controls.addresses.controls; let i=index" >
              <span>Address {{i + 1}}</span>
            <div [formGroupName]="i">
                <input type="text" formControlName="street">
                <input type="text" formControlName="postcode">
            </div>
          </div>
        </div>

就像这里的完整工作示例:https://embed.plnkr.co/sUjE1ULYhfDHLNBw2sRv/1

通过输入字段添加表单FormGroup

我想了解如何通过表单输入添加一个全新的FormGroup。 所以以上面的例子为例......

而不是添加到地址数组:

{
  "name": "",
  "addresses": [
    {
      "street": "Baker Street",
      "postcode": "w2"
    },
    {
      "street": "Bond Street",
      "postcode": "w1"
    }
  ]
}

每次添加地址时,都会创建一个新的FormGroup,用户可以为每个via表单输入添加FormGroupName。例如:

{  
   "name":"",
   "home":{  
      "street":"Baker Street",
      "postcode":"w2"
   },
   "work":{  
      "street":"Bond Street",
      "postcode":"w1"
   }
}

1 个答案:

答案 0 :(得分:4)

使用addControl方法可以这样实现:

app.component.html摘录:

        <div class="margin-20">
            <a (click)="addGroup(newName.value)" style="cursor: default">Add Group +</a>
          </div>

app.component.ts摘录:

ngOnInit() {

        this.myForm = this._fb.group({    
        });
    }


 addGroup(newName:string) {

         let data = this._fb.group({
                     foo: ['what a load of foo'],
                     bar: ['see you at the bar']

                    })

        this.myForm.addControl(newName, data);
        document.getElementById('newName').value='';


    }

plunk中的工作示例:

对于为新命名组中添加的每个formControl发布相应输入字段的示例,我创建了此plunk