1

On my NgOnInit() I´m creating a new form like this.

  ngOnInit(){
    this.expenseForm = this.fb.group({
      type: '',
      expenses: this.fb.array([this.buildExpense()])
    })
  }

I have a key called type that starts empty on my object and a key called expenses

these expenses key receive an array every time the user clicks a button.

  buildExpense(): FormGroup {
    return this.fb.group({
      description: '',
      quantity: '',
      price: ''
    })
  }

  addExpense(): void {
    this.expenses.push(this.buildExpense())
  }

Html

  <button class="btn btn-outline-primary add" type="button" (click)="addExpense()">Add Expense</button>

My objective is to remove the last array add on my form group

Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
Hugo Seleiro
  • 2,467
  • 5
  • 26
  • 39
  • 1
    See https://stackoverflow.com/questions/41852183/angular-2-remove-all-items-from-a-formarray **Beware** https://angular.io/api/forms/FormArray#adding-or-removing-controls-from-a-form-array *Adding or removing controls from a form array To change the controls in the array, use the push, insert, removeAt or clear methods in FormArray itself. These methods ensure the controls are properly tracked in the form's hierarchy. Do not modify the array of AbstractControls used to instantiate the FormArray directly, as that result in strange and unexpected behavior such as broken change detection.* – Andrew Allen Jun 13 '19 at 18:06
  • @AndrewAllen Thank you very much – Hugo Seleiro Jun 13 '19 at 18:32

2 Answers2

5

I think you want to remove the last element of the formArray expenses. To first create the get() for expenses as follows

get expenses(): FormArray {
    return this.expenseForm.get('expenses') as FormArray;
  }

Then to remove the last element from formArray expenses

deleteExpense()
{
  if(this.expenses.length > 0)
  this.expenses.removeAt(this.expenses.length-1);
}
1

As per my undestanding from the question you want to remove the last array , so use the pop method say if there is delete method:

<button class="btn btn-outline-primary add" type="button" (click)="deleteExpense()">Delete Expense</button>

SO we can create a method

     deleteExpense() : void {
    let index = this.expenses.length-1;
 if(index){
        (this. expenseForm.get(
          'expenses'
        ) as FormArray).removeAt(index);
      }
}
Manrah
  • 556
  • 3
  • 13