I am currently in the process of setting up nested formGroup fields using HTML code.
<form [formGroup]="userProfileForm" (ngSubmit)="bookUser()" class="form">
<!-- userName -->
<div class="form-group">
<label for="userName">Name:</label>
<input type="text" class="form-control" id="userName" formControlName="userName">
</div>
<!-- mobile -->
<div class="form-group">
<label for="mobileNumber">Mobile:</label>
<input type="text" class="form-control" id="mobileNumber" formControlName="mobileNumber">
</div>
<!-- emailId -->
<div class="form-group">
<label for="emailId">Email id:</label>
<input type="text" class="form-control" id="emailId" formControlName="emailId">
</div>
<!-- password -->
<div class="form-group">
<label for="password">Password:</label>
<input type="text" class="form-control" id="password" formControlName="password">
</div>
<!-- address -->
<div class="form-group">
<div formGroupName="address">
<label for="city">City:</label>
<input type="text" class="form-control" id="city" formControlname="city">
<label for="state">State:</label>
<input type="text" class="form-control" id="state" formControlname="state">
<label for="zipCode">Zip Code:</label>
<input type="text" class="form-control" id="zipCode" formControlname="zipCode">
</div>
</div>
<button type="submit" class="btn btn-primary">Create Profile</button>
</form>
Below is the TypeScript code i have implemented...
ngOnInit() {
this.userProfileForm=this.formBuilder.group({
userName:['', Validators.required],
mobileNumber:['', Validators.required],
emailId:['', Validators.required],
password:['', Validators.required],
address: this.formBuilder.group({
city:['', Validators.required],
state:['', Validators.required],
zipCode:['', Validators.required]
})
});
}
When I attempt to print the city
formControl value from the child formGroup, it does not display on the HTML. I have tried accessing the value through various methods such as:
(<FormGroup>this.userProfileForm.get('address')).get('city').value;
and
this.city=this.userProfileForm['controls'].address['controls'].city.value
but I still cannot retrieve the city field to show in the HTML.
I also checked with this.city=this.userProfileForm['controls'].address['controls'].city.valid
, which consistently returns false.
I have defined two model classes as well: UserProfile
import { Address } from "./address";
export class UserProfile{
userName:string;
emailId:string;
password:string;
mobileNumber:string;
address:Address;
}
Address
export class Address{
city:string;
state:string;
zipCode:string;
}
How can I successfully access the values within the nested formGroup? What am I missing here?