Search code examples
angularangular-forms

how to make dynamic tables in angular 9


I have the knowledge to create a form in angular 9.

    import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
    this.form = this.fb.group({
       name: [null, [Validators.required]],
       description: [null, []],
       length: [0, [Validators.required]],
       precision: [0, [Validators.required]],
       type: [0, [Validators.required]],
    });

the code above would make a simple form like the one below

simple form

Right now I want to make a dynamic form, which is composed of multiple lines of the simple form above. So the user can add / remove one line of simple form.

dynamic form

I think it needs to apply the methods like addControl and removeControl in the FormBuilder class in angular but how to specific implement it


Solution

  • Your FormGroup should contain a FormArray and in this one, you have to add controls as you described.

    So, first of all you have to change your form declaration like this:

    this.form = this.formBuilder.group({
        entries: this.formBuilder.array([]);
     });
    

    And in this way, you will be able to add/remove controls.

    You can define a method which will return a FormGroup of your type:

    createFormGroup(): FormGroup {
      return new FormGroup({
           name: [null, [Validators.required]],
           description: [null, []],
           length: [0, [Validators.required]],
           precision: [0, [Validators.required]],
           type: [0, [Validators.required]],
       })
    }
    

    Then you have to define some methods to add/remove a FormGroup to/from FormArray:

    addFormGroup(): void {
       this.formEntries.push(this.createFormGroup());
    }
    
    deleteFormGroup(index: number): void {
       this.formEntries.removeAt(index);
    }
    
    get formEntries(): FormArray {
       return this.form.controls.entries as FormArray;
    }
    

    In the HTML you have to list each FormGroup from your FormArray:

    <button (click)="addFormGroup()"> ADD </button>
    
    <form [formGroup]="form">
       <div formArrayName="entries">
          <div *ngFor="let entry of formEntries.controls; let i = index" [formGroupName]="i">
            <!-- add each FormControl -->
    
            <button (click)="deleteFormGroup(i)"> DELETE </button>
          </div>
       </div>
    </form>