Amar A
Amar A

Reputation: 65

Uncaught (in promise): Error: formGroup expects a FormGroup instance. Please pass one in Angular 4

I am unable to solve this issue. The code is copied from Angular docs.

TS File:

export class FormsPage {
  todo: FormGroup;
  constructor(private formBuilder: FormBuilder) {
    this.todo = this.formBuilder.group({
      title: ['', [Validators.required, Validators.minLength(5)]],
      description: [''],
    });
    this.todo.valueChanges.subscribe(data=>this.todoOnDataChange(data));
  }
  todoOnDataChange(data: any): void {
     console.log(data);
  }
  logForm(){
    console.log(this.todo.value)
  }
}

HTML File

<form [formGroup]="todo" (ngSubmit)="logForm()">
    <ion-item>
      <ion-label>Todo</ion-label>
      <ion-input type="text" formControlName="title"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>Description</ion-label>
      <ion-textarea formControlName="description"></ion-textarea>
    </ion-item>
    <button ion-button type="submit" [disabled]="!todo.valid">Submit</button>
  </form>

What's wrong with the code? I just need to develop a form and onSubmit it should call a specified question.

Upvotes: 0

Views: 1260

Answers (3)

Prithivi Raj
Prithivi Raj

Reputation: 2736

Added Formcontrol for variables. please check with the below code.

export class FormsPage {
      todo: FormGroup;
      title : FormControl;
      description : FormControl;
      constructor(private formBuilder: FormBuilder) {
      this.title = new FormControl("", Validators.compose([Validators.required, Validators.minLength(5)]));
      this.description = new FormControl();
        this.todo = formBuilder.group({
          title: this.title,
          description: this.description
        });
        this.todo.valueChanges.subscribe(data=>this.todoOnDataChange(data));
      }
      todoOnDataChange(data: any): void {
         console.log(data);
      }
      logForm(){
        console.log(this.todo.value)
      }
    }

Update - 1 Above code is written on Module file instead of Component file. issue got resolved after moving the code.

Upvotes: 1

Suraj Rao
Suraj Rao

Reputation: 29635

It looks like it is happening in your HTML. [formGroup]="todo" may be set before your form is initialized. Set it in an ng-container with an *ngIf to wait for the form to be initialized.

<ng-container *ngIf="todo">
    <form [formGroup]="todo" (ngSubmit)="logForm()">
    //...
    </form>
</ng-container>

Upvotes: 0

Jithil P Ponnan
Jithil P Ponnan

Reputation: 1247

Did you import the FormGroup?

import { FormControl, FormGroup, Validators } from '@angular/forms';

Upvotes: 0

Related Questions