【问题标题】:Error on creating dynamic FormControl in Angular在 Angular 中创建动态 FormControl 时出错
【发布时间】:2018-10-21 14:02:41
【问题描述】:

在 Angular 中创建动态 FormControl 时出错,控制台抛出以下错误:

错误错误:formGroup 需要一个 FormGroup 实例。请传一个。

用于跟随角度分量

import { Component, OnInit } from "@angular/core";
import { FormGroup, FormControl } from "@angular/forms";

@Component({
  selector: "app-dynamic-form",
  template: `
    <form [formGroup]="form">
      <div *ngFor="let prop of personProps">
        <input type="text" [formControlName]="prop">
      </div>
    </form>
    <pre>{{form.value | json }}</pre>
  `,
  styles: []
})
export class DynamicFormComponent implements OnInit {
  form: FormGroup;
  person: {
    firstname: "Hozefa";
    age: 23;
  };
  personProps = [];

  constructor() {}

  ngOnInit() {
    const formDataObj = {};
    for (const prop of Object.keys(this.person)) {
      formDataObj[prop] = new FormControl(this.person[prop]);
      this.personProps.push(prop);
    }

    this.form = new FormGroup(formDataObj);
  }
}

【问题讨论】:

    标签: angular angular-reactive-forms


    【解决方案1】:
    person: {
        firstname: "Hozefa";
        age: 23;
      };
    

    对象定义错误,替换为:

    person = {
        firstname: "Hozefa",
        age: 23
      };
    

    StackBlitz Demo

    【讨论】:

    • 非常感谢...新手错误
    猜你喜欢
    • 1970-01-01
    • 2020-06-09
    • 2020-10-22
    • 1970-01-01
    • 2019-09-30
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    相关资源
    最近更新 更多