Ammad Nazir
Ammad Nazir

Reputation: 161

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

Upvotes: 4

Views: 46391

Answers (2)

Gopal
Gopal

Reputation: 673

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);
    }
}

Upvotes: 1

prettyfly
prettyfly

Reputation: 3130

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()

Upvotes: 5

Related Questions