SVK
SVK

Reputation: 2197

Angular 4 Error: formGroup expects a FormGroup instance

I get the folowing error provided in screenshot. I am creating a LOGIN form in Angular 4.

enter image description here

Here is the current code with the error.

app.module.ts

 import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { ReactiveFormsModule } from '@angular/forms';

    import { AppComponent } from './app.component';
    import { ProductComponent } from './product/product.component';
    import { MembersComponent } from './members/members.component';
    import { SortPipe } from './app.sortpipe';

    @NgModule({
      declarations: [
      SortPipe,
        AppComponent,
        ProductComponent,
        MembersComponent
      ],
      imports: [
        BrowserModule,
        ReactiveFormsModule
     ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

HTML

<form class="container" [formGroup]="myGroup" (ngSubmit)="onSubmit(myGroup.value)">
<input type="text" name="firstName" placeholder="firstName" formControlName="firstName"/>
<br/><br/>
<input type="text" name="lastName" placeholder="lastName" formControlName="lastName"/>
<br/><br/>
<select name="gender" formControlName="gender">
<option value="female">female</option>
<option value="male">male</option>
</select>
<br/><br/>
<input type="submit" value="submit">
</form>
<br/><br/><br/>

app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  onSubmit= function (user){
  console.log("user",user);
  }


  myGroup ;

  ngOnInIt(){
   this.myGroup = new FormGroup({

  firstName : new FormControl("umair"),
 lastName : new FormControl(""),
  gender  : new FormControl(""),
  })

  }


}

Any help/pointing me in the right direction would be great! Thanks!

Upvotes: 0

Views: 2449

Answers (1)

altschuler
altschuler

Reputation: 3922

There's a typo in your ngOnInIt. It should be ngOnInit. Because of the typo, the method is not run when the component initializes and thus myGroup is undefined.

To avoid this kind of error you should always have your component implement the corresponding interfaces from angular. This example is exactly why they're there :)

In your example it would be:

import { Component, OnInit } from '@angular/core';

export class AppComponent implements OnInit { ... }

This way you will get a compile-time error telling you that AppComponent is not implementing OnInit if you've misspelled or forgotten it.

Upvotes: 4

Related Questions