Angular 2个动态生成的表单组

Angular 2 dynamically generated form group

我正在尝试动态生成一个 FormBuilder 组,但我被生成的组对象卡住了。我有以下组件用于单个 .html 输入字段。

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

加载应用程序时,我在控制台中收到以下错误。

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

home.component.html如下

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

我希望这是我错过的显而易见的事情。

查看 formControlName

documentation

您需要声明 formGroup(您已经完成),以及控件(缺少这一部分)。

const jobGroup = new FormGroup({
    // declare number here
    number: new FormControl()
});

我怀疑你这里有两个错误:

1) this.obj[key] 应该是关键

2) 您不需要使用参数 FormGroup

调用 formBuilder.group
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