Getting values out of Angular form group

2.9k Views Asked by At

I'm new to Angular and I'm trying to create a dynamic table where you can add new columns, rows, and data. The issue that I'm having is with getting the input data from a form group and pushing it into an object that the table is reading from.

The initial group looks like this, and each control appears as a column.

input = new FormGroup({
   name: new FormControl(),
   age: new FormControl(),
   height: new FormConrol()
});

So when you add a column a new control is added using 'input.addControl()'.

Without adding any new columns I could easily push this to the data source but saying,

this.dataSource.push({name: this.input.value.name}) // and so forth

But when new columns are added I have no idea how to push the values to this dataSource variable, since they could be called anything.

Is there a way to say iterate the form groups values and push them like that or something along those lines... Any help would be greatly appreciated.

1

There are 1 best solutions below

0
On BEST ANSWER

What you actually need is a FormArray and not FormGroup. FormArray works more like an Array. You can push values and remove values from it

In the below example I am implementing FormBuilder to generate the FormGroup and FormArray

export class AppComponent {
 
  addInput({ name, age, height }: IFormItem = {}) {
    this.inputs.push(
      this.fb.group({
        name: [name, []],
        age: [age, []],
        height: [height, []]
      })
    );
  }
  removeInput(i: number) {
    this.inputs.removeAt(i);
    this.inputs.updateValueAndValidity();
    this.myForm.updateValueAndValidity();
  }
  myForm = this.fb.group({
    inputs: this.fb.array([])
  });

  get inputs() {
    return this.myForm.get("inputs") as FormArray;
  }
  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.addInput({
      name: 'Test Name',
      age: 5,
      height: 45
    });
    this.addInput();
  }
}

In the HTML

<form [formGroup]='myForm'>
  <button (click)='addInput()'>Add</button>
  <table formArrayName='inputs'>
    <tr>
      <th>#</th>
      <th>Name</th>
      <th>Age</th>
      <th>Height</th>
    </tr>
    <tr *ngFor="let input of inputs.controls; let i = index" [formGroupName]='i'>
      <td>{{ i + 1}}</td>
      <td><input formControlName='name'></td>
      <td><input formControlName='age'></td>
      <td><input formControlName='height'></td>
      <td><button (click)='removeInput(i)'>Delete</button></td>
    </tr>
 </table>
</form>

See this stackblitz demo