I have created a formGroup in angular 4 where user & organization are stored in object. Now i want to populate my formgroup using these two objects. In my ts I have done the following:
createForm(user: any) {
this.userForm = this.fb.group({
name: user.profileData.name,
email: user.profileData.email,
phone: user.profileData.mobileNumber,
orgForm: this.fb.group({
name: [ user.organisation.name , [Validators.required]]
})
});
}
And in my view , I am doing something like this:
<form [formGroup]="userForm" class="user-form" (ngSubmit)="onSubmit()" novalidate>
<div fxLayout="row">
<div fxLayout="column" fxFlex="50%">
<div class="form-group">
<md-input-container class="full-width">
<input mdInput placeholder="User Name" formControlName="name">
</md-input-container>
</div>
<div class="form-group">
<md-input-container class="full-width">
<input mdInput placeholder="User Email" formControlName="email">
</md-input-container>
</div>
<div class="form-group">
<md-input-container class="full-width">
<input mdInput placeholder="User Phone" formControlName="phone">
</md-input-container>
</div>
<div class="form-group">
<button md-raised-button type="submit" [disabled]="userForm.pristine">Save</button>
</div>
</div>
<div fxLayout="column" fxFlex="50%" formGroupName="orgForm">
<div class="form-group">
<md-input-container class="full-width">
<input mdInput placeholder="Organization Name" formControlName="name">
</md-input-container>
</div>
</div>
</div>
</form>
But I am getting the below error:
formGroup expects a FormGroup instance , please pass one in
Any Inputs?
If you're not creating the form in the component's constructor, the first time that the view is being rendered userForm is probably undefined and that's why you're getting that error. Encapsulate your form tag into something like this:
<div *ngIf='userForm'>
</div>
So the form view is only generated when the model has been set.