Angular2 reactive form containing a list

前端 未结 1 779
囚心锁ツ
囚心锁ツ 2021-02-14 12:06

I am attempting to create a form for a user that will allow one to may phone numbers to be associated with the user. Is this possible with the current implementation of reactive

1条回答
  •  醉梦人生
    2021-02-14 12:46

    What you want to use is a FormArray where you can add new Form Controls dynamically:

    constructor(private fb: FormBuilder) {  }
    
    // build form
    this.userForm = this.fb.group({
      numbers: this.fb.array([
        new FormControl()
      ])
    });
    
    
    // push new form control when user clicks add button
    addNumber() {
      const control = this.userForm.controls['numbers'];
      control.push(new FormControl())
    }
    

    And then your template:

    Demo

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