4

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

Ammad Nazir
  • 161
  • 1
  • 4
  • 15

2 Answers2

5

You can get an individual data value from your FormGroup with:

this.DataForm.get('<enter control name>').value

e.g, if your formcontrol is 'email':

this.DataForm.get('email').value

Or, you can get the entire form value as an object with:

this.DataForm.getRawValue()

prettyfly
  • 2,962
  • 1
  • 25
  • 27
  • form control name is not fixed coming from database, you can never guess what value show up next with what name. – Ammad Nazir Feb 26 '19 at 13:53
  • `this.DataForm.getRawValue()` will still return an object, with the values associated with the keys. Irrespective of what the `FormData` object looks like. – prettyfly Feb 26 '19 at 14:00
  • issue i am getting now -- Cannot find control with name: valueName if i add [formControlName]="data.name", if i remove [formControlName]: i get this error
    – Ammad Nazir Feb 26 '19 at 14:02
  • What is the structure of `DataForm`? Have your created it with `FormBuilder` (reactive forms), or are you attempting Template driven forms? By your snippet, neither are implemented properly. – prettyfly Feb 26 '19 at 14:16
  • If you're building a `FormGroup`, you need to use `formControlName` in your template, if you're using template driven, you need `(ngModel)`... you have neither. – prettyfly Feb 26 '19 at 14:17
1

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);
    }
}
Gopal
  • 603
  • 10
  • 18