Array of numbers in Reactive Forms, Angular 6?

Mohammad Dayyan picture Mohammad Dayyan · Jul 3, 2018 · Viewed 10.9k times · Source

I know we can add array of object to FormGroup with FormArray as follows:
https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/

ngOnInit() {
  this.orderForm = this.formBuilder.group({
    customerName: '',
    email: '',
    items: this.formBuilder.array([ this.createItem() ])
  });
}

createItem(): FormGroup {
  return this.formBuilder.group({
    name: '',
    description: '',
    price: ''
  });
}

addItem(): void {
  this.items = this.orderForm.get('items') as FormArray;
  this.items.push(this.createItem());
}

<div formArrayName="items"
  *ngFor="let item of orderForm.get('items').controls; let i = index;">
  <div [formGroupName]="i">
    <input formControlName="name" placeholder="Item name">
    <input formControlName="description" placeholder="Item description">
    <input formControlName="price" placeholder="Item price">
  </div>

  Chosen name: {{ orderForm.controls.items.controls[i].controls.name.value }}
</div>

But I want to have array of number not object.
How can we do it in Angular 6.*?
How can we add or remove number item from it?

Answer

smnbbrv picture smnbbrv · Jul 3, 2018

You can pass any form control instead of form group to the form array:

new FormGroup({
  // ...
  items: new FormArray([new FormControl(123)]),
});

Possible controls that are shipped with angular: FormGroup, FormArray, FormControl.

FormBuilder (which I personally find obsolete, just an opinion) just creates those objects for you. If you want to stick with it try

items: this.formBuilder.array([123])

Add and remove Item:

private addItem(value: number) {
    this.itemsFormArray.push(new FormControl(value));
}
private removeItem(value: number) {
    let index = this.itemsFormArray.controls.findIndex(control => { 
        return control.value == value;
    });
    this.itemsFormArray.removeAt(index);
}
private get itemsFormArray(): FormArray {
    return this.formGroup.get('items') as FormArray;
};