Angular

Last Updated: 8/30/2023

Creating Controls Programmatically

  • Open the component
  • Import formcontrol, formgroup
import {FormGroup, FormControl} from '@angular/forms'
  • Create an instance of formGroup
  • Parameter 1 includes the controls that are part of the form
  • Pass key value pairs, key is string and value is type ofAbstractControl
  • In OOPs, Inheritance: If we have multiple class that should have common behavior and properties, instead of implementing multiple times we define them once in parent or base class and other class inherit the properties and behavior from base class
  • AbstractControl is base class for FormControl and FormGroup
form = new FormGroup({
	username: new FormControl(),
	password: new FormControl()
})
  • For subgroup use new FormGroup
  • Use single quotes in the key, if it is not valid key in javascript
  • In template, associate our input field with these form control objects
  • Add formGroup directive associate the formgroup object with the form element
<form [formGroup]="form">
  • Add formControlName directive and set to the name of key in form group object
<input formControlName="username">
<input formControlName="password">
  • Import ReactiveModule in app.module.ts
import {ReactiveFormsModule} from '@angulars/forms';
imports: [ReactiveFormsModule]