Angular / Form / Step 6: Create Form
Create a form
-
in module.ts
Step 1: import FormsModule, ReactiveFormsModule
import { FormsModule, ReactiveFormsModule } from '@angular/forms'; Step2: add FormsModule,ReactiveFormsModule into imports[]
imports: [ FormsModule,ReactiveFormsModule], -
in components
Step1: import FormBuilder, FormGroup
import { FormBuilder, FormGroup } from '@angular/forms'; 1) FormGroup will be used in the STEP 2 for variable declaration
2) FormBuilder will be used in STEP 3 to inject into constroctor()Step2: declare formGroup variable
mainForm: FormGroup; ... .... constructor(){ } Step3: inject 'FormBuilder' into constroctor()
constructor( private fb: FormBuilder,) { } Step4: define mainForm (FormGroup)
this.mainForm = this.fb.group({ 'name': [''], 'symbol':[''], 'parent_id' :[''] }); 1) mainForm will be used in the html inside the form tag
2) name ,symbol and parent_id are formContol. These will be used for formControlName inside the form tag -
in view page
Step1: link the formGroup with form
Step2: link the formGroup elements inside the form tag
Code