Turning a form into a dynamic form

The FormGroup is the construct that consists of many form controls. To create such a construct we need to do the following:

  1. Import the reactive Forms module.
  2. Instantiate as many FormControls as you need, through code.
  3. Place the controls in a dictionary.
  4. Assign the dictionary as input to the FormGroup.
  5. Associate our Form group instance with the [formGroup] directive.
  6. 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:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset