Angular2 form ControlGroup who hold an undefined number of Control

前端 未结 1 1263
萌比男神i
萌比男神i 2020-12-19 12:36

How to manage with Angular2 a form who hold an undefined number of field ?

In my case, I need to create a from where user can add and delete some block of fileds. It

1条回答
  •  隐瞒了意图╮
    2020-12-19 13:13

    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: `
        

    Add address

    • {{ctrl}}:
    Add Another Address
    `, 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) }); (this.userForm.find('addresses')).addControl( 'address' + (Object.keys((this.userForm.find('addresses')).controls).length + 1), addressField); } }

    0 讨论(0)
提交回复
热议问题