Angular 2动态生成的表单组

MindVox

我试图动态地生成一个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>

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

yurzui

我怀疑您在这里有两个错误:

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

柱塞示例

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章