The requirement is to dynamically create a group of form fields
This can be very easily achieved using a nested form group. So, first let’s create a nested form group for skill related fields in the component class.
Step 1: Creating a nested form group in the component class : Form groups can accept both form control and form group instances as children. This allows us to create a nested form group.
ngOnInit() {
this.employeeForm = new FormGroup({
fullName: new FormControl(),
email: new FormControl(),
// Create skills form group
skills: new FormGroup({
skillName: new FormControl(),
experienceInYears: new FormControl(),
proficiency: new FormControl()
})
});
}
Add new formGroup(skills) within existing employeeForm
Notice we have created a nested form group with key – skills. This nested form group contains 3 form controls.
skillName,
experienceInYears and
proficiency
Step 2: Grouping the nested form in the template : To group the form elements in the HTML, encapsulate the form elements in a div element and use the formGroupName directive on that container div element. Bind the formGroupName directive to the skills FormGroup instance in the component class. Bind each input element in the HTML, to the corresponding FormControl instance using the formControlName directive.
