Angular 2动态生成表单组

时间:2017-03-06 09:34:27

标签: angularjs angular typescript formbuilder

我正在尝试动态生成一个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>

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

2 个答案:

答案 0 :(得分:3)

我怀疑你有两个错误:

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

2)您不需要使用参数formBuilder.group

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

答案 1 :(得分:-1)

查看formControlName的documentation

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

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