Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 dynamically generated form group

I am trying to dynamically generate a FormBuilder group and I am stuck with the generated group object. I have the following component which is for a single .html input field.

import { Component, onInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';

@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {
    job: any;

    constructor(
        public formBuilder: FormBuilder
    ) {
        this.job = {
            number: 'J001'
        }
    }

    ngOnInit() {
        const jobGroup: FormGroup = new FormGroup({});
        for (const key in this.job) {
            if (this.job.hasOwnProperty(key)) {
                const control: FormControl = new FormControl(this.job[key], Validators.required);
                jobGroup.addControl(this.job[key], control);
            }
        }

        this.jobForm = this.formBuilder.group(jobGroup);
    }
}

When the application loads, I get the following error in the console.

Error: Error in ./HomeComponent class HomeComponent - inline template:12:50 caused by: Cannot find control with name: 'number'

The home.component.html is as follows.

<form [formGroup]="jobForm" novalidate>
    <div class="form-group">
      <label class="control-label" for="number">Job Number</label>
      <input type="text" class="form-control" formControlName="number" id="number">
    </div>

    <button class="btn btn-success btn-block">Save Record</button>
</form>

I am hoping that this is something obvious that I have missed.

like image 613
stackunderflow Avatar asked Feb 04 '23 23:02

stackunderflow


1 Answers

I suspect you have two mistakes here:

1) this.obj[key] should be key

2) you don't need to call formBuilder.group with parameter FormGroup

const jobGroup: FormGroup = new FormGroup({});
for (const key in this.job) {
  if (this.job.hasOwnProperty(key)) {
    const control: FormControl = new FormControl(this.job[key], Validators.required);
    jobGroup.addControl(key, control); // instead of this.obj[key]
  }
}

this.jobForm = jobGroup; // jibGroup is already formGroup

Plunker Example

like image 172
yurzui Avatar answered Feb 07 '23 13:02

yurzui