Search code examples
angulartypescriptdynamicform

how to get value from dynamic form in angular


how do i get values from angular dynamic form here is my code: my html

<form (ngSubmit)="PreviewData()" [formGroup]="DataForm">
<div class="form-group row" *ngFor="let data of FormData;" >
        <label class="col-md-2 col-form-label" >{{data.name}}</label>
        <div class="col-md-10">
          <input type="text" class="form-control"  name="{{data.name}}">
        </div>
      </div>
<button class="btn btn-primary float-right" type="submit" >Preview</button>
</form>

in my typescript file

PreviewData() {
    this.payLoad = JSON.stringify(this.DataForm.value);
}

how do i get values in from group data in ts file


Solution

  • add the formControl using functions.

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { FormGroup, FormArray, Validators, FormControl } from '@angular/forms';
    
    @Component({
      selector: 'app-sample-reactive-form',
      templateUrl: './sample-reactive-form.component.html',
      styleUrls: ['./sample-reactive-form.component.css']
    })
    
    export class SampleReactiveFormComponent
    {
    
      payLoad: any;
      FormData: any;
      DataForm: FormGroup = new FormGroup({});
    
      constructor()
      {
        this.FormData = [{
          name:'a'
        },{
          name:'b'
        }]
    
        this.DataForm = this.generateFormControls(this.FormData);
     }
    
        generateFormControls(formData: any)
        {
            let tempGroup: FormGroup = new FormGroup({});
            formData.forEach(i=>{
                tempGroup.addControl(i.name, new FormControl(''))
            })
            return tempGroup;
        }
    
        PreviewData() 
        {
             this.payLoad = JSON.stringify(this.DataForm.value);
        }
    }