The FormGroup is the construct that consists of many form controls. To create such a construct we need to do the following:
- Import the reactive Forms module.
- Instantiate as many FormControls as you need, through code.
- Place the controls in a dictionary.
- Assign the dictionary as input to the FormGroup.
- Associate our Form group instance with the [formGroup] directive.
- Associate each FormControl instance to a [formControlName] directive.
The first step lies in importing the module:
@NgModule({
imports: [ReactiveFormsModule]
})
The second step is creating form controls. Let's create two different ones, one with validation and one without:
const control = new FormControl('some value');
const control2 = new FormControl('other value', Validators.required);
The third step is to create a dictionary for this:
const group = {};
group['ctrl1'] = control;
group['ctrl2'] = control2;
The fourth step is to assign the group to a formGroup instance:
const formGroup = new FormGroup(group);
Your full code should look something like this:
import { FormControl, FormGroup } from '@angular/forms';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'dynamic',
template: `
dynamic
<div [formGroup]="form">
dynamic
<input [formControl]="group['ctrl1']" placeholder="name">
</div>`
})
export class DynamicComponent implements OnInit {
form:FormGroup;
group;
constructor() {
this.group = {};
this.group['ctrl1'] = new FormControl('start value');
this.form = new FormGroup(this.group);
}
ngOnInit() { }
}
Your form's UI should look like this. As you can see, your start value is set to the input control: