Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 438
Ammad Nazir Avatar asked Sep 14 '25 01:09

Ammad Nazir


2 Answers

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

like image 127
prettyfly Avatar answered Sep 16 '25 19:09

prettyfly


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);
    }
}
like image 37
Gopal Avatar answered Sep 16 '25 19:09

Gopal