Search code examples
angularionic-frameworkionic3angular4-forms

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.


Solution

  • 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.