There are two types of form you can use with Angular “Template driven” and “Reactive” (also known as “Model driven”).
Template driven forms rely on the html to deal with the majority of the form building. See below for a Template driven form. This binds a property from our component class to the value of the input element. You must have a name element in order for this to work effectively. #firstNameVar is the template reference variable to access the form control instance this allows for some error validation. Angular does a lot of our work for us in the template driven approach however it is less flexible. NgModel gives us the two way binding.
The second type of form in Angular is the Reactive form. In this approach we create the form module (which angular deals with under the hood in the Template based approach.
Component:
import { Component, OnInit } from '@angular/core' import { FormGroup, FormControl } from '@angular/forms' export class OurComponent implements OnInit { customerForm: FormGroup; customer: Customer = new Customer(); ngOnInit(): void { this.customerForm = new FormGroup({ firstName: new FormControl('default') }); } }
Remember to add ReactiveFormsModule to the declarations of the Module!
Creating the Reactive Form:
We can now use the formgroups get method i.e. customerForm.get(‘firstName’).valid in the html.