How to use formControlName and deal with nested formGroup?
It is true. Look at formGroupName
this.myForm = fb.group({
'fullname': ['', Validators.required],
'gender': [],
'address': fb.group({
'street': [''],
'houseNumber': [''],
'postalCode': ['']
})
});
<form [formGroup]="myForm" >
<div class="form-group">
<label for="fullname">Username</label>
<input type="text" id="username" formControlName="fullname" class="form-control">
</div>
<div class="radio" *ngFor="let gender of genders">
<label>
<input type="radio" formControlName="gender" [value]="gender">{{ gender }} </label>
</div>
<div formGroupName="address">
<div class="form-group">
<label for="street">Username</label>
<input type="text" id="username" value="street" formControlName="street" class="form-control">
</div>
<div class="form-group">
<label for="houseNumber">Username</label>
<input type="text" id="username" value="street" formControlName="houseNumber" class="form-control">
</div>
<div class="form-group">
<label for="postalCode">Username</label>
<input type="text" id="username" value="street" formControlName="postalCode" class="form-control">
</div>
</div>
</form>
you can use Form group which is basically a collection of controls ( controls mean the fields given in your html form) define in your typescript syntax and binded to your HTML elements using the formControlName directive ,for example
this.myForm = fb.group({
'fullname': ['', Validators.required],
'gender': [],
'address': fb.group({
'street': [''],
'houseNumber': [''],
'postalCode': ['']
})
});
Template:
<form [formGroup]="myForm" >
<div class="form-group">
<label for="fullname">Username</label>
<input type="text" id="username" formControlName="fullname" class="form-control">
</div>
<div class="radio" *ngFor="let gender of genders">
<label>
<input type="radio" formControlName="gender" [value]="gender">{{ gender }} </label>
</div>
<div formGroupName="address">
<div class="form-group">
<label for="street">Username</label>
<input type="text" id="username" value="street" formControlName="street" class="form-control">
</div>
<div class="form-group">
<label for="houseNumber">Username</label>
<input type="text" id="username" value="street" formControlName="houseNumber" class="form-control">
</div>
<div class="form-group">
<label for="postalCode">Username</label>
<input type="text" id="username" value="street" formControlName="postalCode" class="form-control">
</div>
</div>
</form>
A formGroup can consist of a nested formGroup and hierarchy can continue on ,but in accessing the value the its fairly simple .