Creating a Typed Reactive Angular Contact Form

Scenario
We need a typed and reactive Contact
form that gives us autocompletion for the form fields in our IDE and also provides error linting if we try to access fields that are not in the form.
Approach
Project Setup
We will create a Stackblitz and add @angular/material
to the dependencies for the form UX.
Also to index.html
add the link for Material Icons.
<linkhref="https://fonts.googleapis.com/icon?family=Material+Icons"rel="stylesheet"/>
and to styles.scss
add the indigo pink theme.
@import '~@angular/material/prebuilt-themes/indigo-pink.css';
Initialize app.module.ts
.
Form Interface
First in app.component.ts
define the interface for the form controls.
//===========================================
// Contact Form Interface
//===========================================export interface IContactForm {
name: FormControl<string>;
email: FormControl<string>;
phone?: FormControl<string | null>;
}
In the youtube that goes along with this article we point out the additional benefits of this interface.
Next define the form itself.
Note that we are passing in the Type of the form in the form constructor IContactForm
.
Then bind the form controls to the template.
Demo
Here’s the demo again.