CodePráticov3.3.0
Angular

FormArray no Angular com exemplo prático

Crie formulários dinâmicos no Angular usando FormArray para adicionar e remover telefones, itens, ingredientes ou outras linhas.

Criar o formulário

form = this.fb.group({
  nome: [''],
  telefones: this.fb.array([])
});

get telefones(): FormArray {
  return this.form.get('telefones') as FormArray;
}

Adicionar uma linha

adicionarTelefone(): void {
  this.telefones.push(
    this.fb.group({
      tipo: ['CELULAR'],
      numero: ['']
    })
  );
}

Remover uma linha

removerTelefone(index: number): void {
  this.telefones.removeAt(index);
}

Template

<div formArrayName="telefones">
  <div
    *ngFor="let item of telefones.controls; let i = index"
    [formGroupName]="i"
  >
    <input formControlName="tipo">
    <input formControlName="numero">
    <button type="button" (click)="removerTelefone(i)">
      Remover
    </button>
  </div>
</div>