Search code examples
angularangular-reactive-formsangular-forms

Add a row to table on click of add button the new row is form fields in each cell


Actually on add click I need to add row its getting added but I am not able to get the ngmodel object Or Is there any other best way to implement using reactive forms so finally requirement is to get a row on add click and get the form value best way of implementation or please modify the above code

Stackblitz Link


Solution

  • Check live demo here.

    http://keepnote.cc/code/form-group-with-formarray-adding-dyamic-row-angular-5-6

    Please check this.

    We have to use FormBuilder and FormBuilder.array for dynamic rows.

    html

    <form [formGroup]="carForm" (ngSubmit)="saveIntergration()">
        <div formArrayName="details" class="form-group" *ngFor="let field of carForm.get('details').controls; let ind = index;">
            <div [formGroupName]="ind">
                Type:
                <input type="text" formControlName="type">
    
                model:
                <input type="text" formControlName="model">
    
                year:
                <input type="text" formControlName="year">
    
                make:
                <input type="text" formControlName="make">
    
                color
                <input type="text" formControlName="color">
    
                plateNumber
                <input type="text" formControlName="plateNumber">
    
                <hr>
            </div>
        </div>
    </form>
    
    <button (click)="addRow()">Add New</button>
    
    <pre>
        {{carForm.value | json}}
    </pre>
    

    ts

    import { Component, ViewChild } from '@angular/core';
    import { FormBuilder, FormGroup, FormControl, Validators, FormArray } from '@angular/forms';
    
    @Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
    
    })
    export class AppComponent {
        public carForm: FormGroup;
        constructor(private fb: FormBuilder) {
    
            const items = [];
            items.push(this.fb.group({
                type: [],
                model: [],
                year: [],
                make: [],
                color: [],
                plateNumber: []
            }));
    
            this.carForm = this.fb.group({
                details: this.fb.array( items )
            });
        }
    
        addRow() {
            const details = this.carForm.get('details') as FormArray;
            details.push(this.createItem());
        }
    
        createItem(): FormGroup {
            return this.fb.group({
                type: [],
                model: [],
                year: [],
                make: [],
                color: [],
                plateNumber: []
            });
        }
    }