Angular2 form ControlGroup who hold an undefined number of Control

偶尔善良 提交于 2019-11-29 11:03:59

I implemented it for you, see Plunker or better yet, Plunker -@waldo

import {Component} from 'angular2/core';
import {
  FORM_DIRECTIVES, FormBuilder, ControlGroup, ControlArray, Validators, NgForm, Control,
  AbstractControl
} from 'angular2/common';

@Component({
  selector: 'my-app',
  template: `
    <form [ngFormModel]="userForm" *ngIf="userForm">
      <p><label><input id="date" type="text" ngControl="name" #name="ngForm"/> Name</label></p>

      <p><label><input id="date" type="text" ngControl="firstName" #firstName="ngForm"/> FirstName</label></p>

      <h3>Add address</h3>
        <ul ngControlGroup="addresses">

        <li *ngFor="#ctrl of objToArray(userForm.find('addresses').controls); #i = index" 
        ngControlGroup="{{ctrl}}">
           {{ctrl}}:
          <input ngControl="street" placeholder="Street">
          <input ngControl="streetNumber"  placeholder="StreetNumber"> 
        </li>
      </ul>

    <div (click)="addAddress()" style="cursor: pointer"> Add Another Address</div>

    </form>

    `,
  directives: [FORM_DIRECTIVES]
})
export class AppComponent {
  userForm: ControlGroup;

  constructor(private fb: FormBuilder) {

    this.userForm = fb.group({
      name: fb.control(null, Validators.required),
      firstName: fb.control(null, Validators.required),
      addresses: fb.group({
        address1: fb.group({
          street: fb.control(null, Validators.required),
          streetNumber: fb.control(null, Validators.required)
        })
      })
    });

    console.log(this.userForm);

  }

  objToArray(o){
    return Object.keys(o);
  }

  addAddress() {
    let addressField = this.fb.group({
      street: this.fb.control(null, Validators.required),
      streetNumber: this.fb.control(null, Validators.required)
    });

    (<ControlGroup>this.userForm.find('addresses')).addControl(
      'address' + (Object.keys((<ControlGroup>this.userForm.find('addresses')).controls).length + 1), addressField);
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!