0

Error on creating dynamic FormControl in Angular, console throws following error:

ERROR Error: formGroup expects a FormGroup instance. Please pass one in.

for following angular component

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

1 Answer 1

2
person: {
    firstname: "Hozefa";
    age: 23;
  };

Object definition is wrong, replace to:

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

StackBlitz Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot ... noob mistake

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.