dynamic froms using reactive froms

Solutions on MaxInterview for dynamic froms using reactive froms by the best coders in the world

showing results for - "dynamic froms using reactive froms"
Luciano
04 Jan 2019
1<div>
2<input type="button" value="select" (click)="test()">
3</div>
4<div>
5  <form [formGroup]="dynamicForm" (submit)="SaveData()">
6 
7    <div *ngFor="let ticket of t.controls; let i = index" class="list-group list-group-flush">
8      <div class="list-group-item">
9        <div [formGroup]="ticket" class="form-row">
10          <div class="form-group col-6">
11            <label>{{ticket.get('paramName').value}}  </label>
12            <input type="text" formControlName="paramValue" class="form-control" />
13          </div>
14        </div>
15      </div>
16    </div>
17    <input type="submit" value="Click Me" />
18  </form>
19</div>
20import { Component, OnInit } from '@angular/core';
21import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
22
23@Component({
24  selector: 'my-app',
25  templateUrl: './app.component.html',
26  styleUrls: ['./app.component.css']
27})
28export class AppComponent implements OnInit {
29  dynamicForm: FormGroup;
30  submitted = false;
31  ParamsData: any = [];
32
33  constructor(private formBuilder: FormBuilder) {}
34  ngOnInit() {
35    this.dynamicForm = this.formBuilder.group({
36      numberOfTickets: ['', Validators.required],
37      tickets: new FormArray([])
38    });
39  }
40
41  // convenience getters for easy access to form fields
42  get f() {
43    return this.dynamicForm.controls;
44  }
45  get t() {
46    return this.f.tickets as FormArray;
47  }
48
49  test() {
50    this.ParamsData = [
51      {
52        paramName: 'oracle_home',
53        paramType: 'string',
54        paramValue: '',
55        mandatory: true
56      },
57      {
58        paramName: 'ogg_home',
59        paramType: 'string',
60        paramValue: '',
61        mandatory: true
62      },
63      {
64        paramName: 'java_home',
65        paramType: 'string',
66        paramValue: '',
67        mandatory: true
68      },
69      {
70        paramName: 'interval',
71        paramType: 'string',
72        paramValue: '',
73        mandatory: true
74      }
75    ];
76    this.createform();
77  }
78  createform() {
79    for (let i = 0; i < this.ParamsData.length; i++) {
80      this.t.push(this.BuildFormDynamic(this.ParamsData[i]));
81    }
82  }
83
84  BuildFormDynamic(product): FormGroup {
85    return this.formBuilder.group({
86      paramName: [product.paramName],
87      paramValue: [product.paramValue],
88      paramType: [product.paramType],
89      mandatory: [product.mandatory]
90    });
91  }
92
93  SaveData() {
94    console.log(this.dynamicForm.value);
95  }
96}
97