Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

214
Vistas
Angular2 reactive form containing a list

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 forms? For example, I would want the below form to accept potentially many phone numbers. My front end implementation would show the phone number field, and would have a button that would allow for an additional phone number field to be added.

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

My hack solution would 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 additional phone fields until the add an additional phone number button is clicked.

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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

And then your template:

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

Demo

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda