Angular2 reactive form listing

I am trying to create a form for a user that allows me to associate phone numbers with a user. Is this possible with the current implementation of reactive forms? For example, I would like the bottom form to accept potentially many phone numbers. My foreground implementation will display a phone number field and will have a button that will add an additional phone number field.

userForm = new FormGroup({
  firstName: new FormControl('', Validators.required),
  lastName: new FormControl('', Validators.required),
  phoneNumber: new FormControl('', Validators.required)
});

My hacking solution will be

userForm = new FormGroup({
  firstName: new FormControl('', Validators.required),
  lastName: new FormControl('', Validators.required),
  phoneNumber: new FormControl('', Validators.required),
  phoneNumber1: new FormControl(),
  phoneNumber2: new FormControl(),
  phoneNumber3: new FormControl(),
  phoneNumber4: new FormControl()
});

I could suppress the extra phone fields until the add additional phone number button is pressed.

+6
source share
1 answer

, FormArray, :

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 = <FormArray>this.userForm.controls['numbers'];
  control.push(new FormControl())
}

:

<form [formGroup]="userForm" (ngSubmit)="submit(userForm.value)">
<div formArrayName="numbers">
  <!-- iterate the array of phone numbers -->
  <div *ngFor="let number of userForm.controls.numbers.controls; let i = index" >
      <label>PhoneNumber {{i+1}} </label>
      <input formControlName="{{i}}" />
  </div>
</div>
<button type="submit">Submit</button>
</form>

+5

Source: https://habr.com/ru/post/1015944/


All Articles