user3692033
user3692033

Reputation: 635

formGroup expects a FormGroup instance. Please pass one in. angular 4

I found multiple solution for this problem but none is working.

This is my angular form

<div class="container">
 <form   [formGroup]="restaurantForm" novalidate>
 <div class="form-group">
  <label for="rating">Rest Name</label>
  <input type="text" class="form-control" formControlName="restName" />
 </div>

<div class="form-group">
  <label for="alterEgo">Description</label>
  <input type="text" class="form-control" formControlName="description" />
</div>

<div [formGroup]="location">

  <div class="form-group">
    <label for="alterEgo">Latitude</label>
    <input type="text" class="form-control" formControlName="latitude">
  </div>
  <div class="form-group">
    <label for="alterEgo">Longitude</label>
    <input type="text" class="form-control" formControlName="longitude">
  </div>
  <div class="form-group">
    <label for="alterEgo">Street</label>
    <input type="text" class="form-control" formControlName="street">
  </div>
  <div class="form-group">
    <label for="alterEgo">Road No</label>
    <input type="text" class="form-control" formControlName="roadNo">
  </div>

</div>

</form>
</div>

<button type="submit" class="btn btn-success" (click)="newRestaurant()">Submit</button>

This is my component where i specified form initialization using Formbuilder and FormGroup.

@Component({
selector: 'restaurant',
templateUrl: 'restaurantForm.component.html'
})

export class ResComponent implements OnInit {

restaurantForm: FormGroup;
restaurants = [];

constructor(private fb: FormBuilder) {
this.restaurantForm = this.fb.group({
  restName: '',
  description: '',
  location: fb.group({
    latitude: '',
    longitude: '',
    street: '',
    roadNo: '',
  })
});
}

ngOnInit() {
}



 newRestaurant() {
 let res = { "restaurant": this.restaurantForm.value };
 this.restaurants.push(res);
 alert(JSON.stringify(this.restaurantForm.value));

 }

}

when i load this form i got an error like "formGroup expects a FormGroup instance. Please pass one in." I tried multiple solution from previous post but none of it working . when i submit form i don't get value from "location" formGroup.

Upvotes: 1

Views: 7682

Answers (1)

Mohamed Ali RACHID
Mohamed Ali RACHID

Reputation: 3297

when you write [formGroup]="location" , it means in your ts there is an instance of FormGroup called location , so you have to pass the instance which is restaurantForm.controls['location']

try : <div [formGroup]="restaurantForm.controls['location']">

instead of : [formGroup]="location"

Hope this help :)

Upvotes: 1

Related Questions