How to implement Angular material form in Angular 11?

We will make series of tutorials on Angular material components and in the article, we will explore how to implement Angular material form in the Angular 11 project. Angular Materials provide the developer with reusable UI components that help the developer to use ready-made components, fast development, and one best UI design. In Angular, we can use different UI libraries, but Angular Material is one of the best UI component libraries that are made specifically for Angular.

We have three objectives behind this tutorial, first will learn how to use Angular material form in reactive form and second we’ll look how used different material component like material form field, material hint, error , date picker, material select and material radio buttons. Last how to apply material icon on these material inputs. Let’s get started.

Step 1: Setting up and configure Angular material form project

Let first create our Angular material form project. In our previous articles, we had learned how to install and the best approach of configuring Angular material in our project. Run the following command to create and add Angular Material to our project.

ng new angularMaterialFormApp
cd angularMaterialFormApp
ng add @angular/material

While running the 3rd command will ask you the select theme, material typography, and animation, press yes on all. To use the Angular material component, we have to import it into our app module. Let create a module and import all material components on it.

ng g m ng-material
Angular material form example

Open src/app/ng-material/ng-material.module.ts and replace the existing code with the code shown below.

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatNativeDateModule } from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatIconModule } from '@angular/material/icon';
import { MatSelectModule } from '@angular/material/select';
import { MatRadioModule } from '@angular/material/radio';
import { MatButtonModule } from '@angular/material/button';

@NgModule({
    declarations: [],
    imports: [
        CommonModule,
        MatTableModule,
        MatSortModule,
        MatFormFieldModule,
        MatInputModule,
        MatDatepickerModule,
        MatNativeDateModule,
        MatInputModule,
        MatIconModule,
        MatSelectModule,
        MatRadioModule,
        MatButtonModule,
    ],
    exports: [
        CommonModule,
        MatTableModule,
        MatSortModule,
        MatFormFieldModule,
        MatInputModule,
        MatDatepickerModule,
        MatNativeDateModule,
        MatInputModule,
        MatIconModule,
        MatSelectModule,
        MatRadioModule,
        MatButtonModule
    ]
})
export class NgMaterialModule { }

We are importing all the required modules in our custom material module file and keeping separate modules for Angular material will make the application easy to maintain. Now we need to import our material module and ReactiveFormModule in our src/app/app.module.ts file.

import { NgMaterialModule } from './ng-material/ng-material.module';
@NgModule({
...
imports: [
   ...
  ReactiveFormsModule,
  NgMaterialModule,
],
})

Step 2: Angular material form example

We have complete our configure of material form, now let demonstrate the Angular material form example. We have learned that Angular has two different types of form, template-driven, and reactive forms. We are using Reactive form to demonstrate Angular material form example. If you have no idea how to used these forms please check our previous tutorial on them, as in this tutorial we are only focused on how to implement material form.

Here is a screenshot of our Angular material form example

angular material form example

Step 3: Initialize form and adding Angular material form validation rule

In our component typescript, we need to add Angular material form validation rules, like required, email validation, min and max length of the input, etc. Now let create a form and add validation in the app.component.ts file

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
  form: FormGroup;

  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.form = this.fb.group({
      name: [null, [Validators.required, Validators.minLength(10)]],
      email: [null, [Validators.required, Validators.pattern("^[a-z0-9._%+-][email protected][a-z0-9.-]+\\.[a-z]{2,4}$")]],
      dob: [null, [Validators.required]],
      address: [null],
      country: [null],
      gender: [null],
      // password: [null, [Validators.required, Validators.minLength(6)]],
      // confirmPassword: [null, [Validators.required]],
    });
  }

  saveDetails(form) {
    alert('SUCCESS!! :-)\n\n' + JSON.stringify(form.value, null, 4));
  }
}

required: This attribute is used to specify a value that must be provided.
minlength: This attribute is used to specify a minimum number of characters.
maxlength: This attribute is used to specify a maximum number of characters. This type of validation cannot be applied directly to form elements because it conflicts with the HTML5 attribute of the same name. It can be used with model-based forms.
pattern: This attribute is used to specify a regular expression that the value provided by the user must match.

Here we don’t have to do anything related to material form, as material components are declared and used inside our component template. We have declared form rules and if the form is valid, then we output it through the alert function.

Step 4: Adding meterial form component in Angular material form template.

Now we will add material form components in our component template, we have used mat-form-field, mat-label, mat-select, mat-radio-button, mat-datepicker-toggle, mat-hint, and mat-error. Here we have listed and uses of material components.

Material componentDescription
mat-form-fieldThe component is used to wrap several Angular Material components and apply common text field styles such as the underline, floating label, and hint messages.
mat-labelThe label component allows indicating a form field as optional by using the optional input property.
mat-selectThe mat-select is form control for selecting a value from a set of options.
mat-radio-buttonProvide the same functionality of radio buttons with material design styles.
mat-datepicker-toggleThe datepicker allows users to enter a date either through text input or by choosing a date from the calendar.
mat-hintIs optional, we can add hints for the input field for validation.
mat-error.how form validation error with this component without any styling
mat-buttonSame HTML button with material design style.

Let edit our material form, in the app.component.html file.

<div class="container">
    <form [formGroup]="form" (ngSubmit)="saveDetails(form)">
        <mat-form-field appearance="standard">
            <mat-label>Name</mat-label>
            <input matInput maxlength="15" inputmode="tel" placeholder="Type name" formControlName="name" #nameInput>
            <mat-hint>Mini character 10: {{ nameInput.value.length }}/10</mat-hint>
            <mat-error>Name is required</mat-error>
            <mat-error **ngIf="(form.get('name')).errors?.minlength">
                Please enter more than 10 character
            </mat-error>
        </mat-form-field>

        <mat-form-field appearance="legacy">
            <mat-label>Email Address:</mat-label>
            <input matInput type="email" formControlName="email" placeholder="Your email">
            <mat-icon matSuffix>mail_outline</mat-icon>
            <mat-hint>Input the fully qualified email address</mat-hint>
            <mat-error *ngIf="(form.get('email')).errors?.required">Email is required</mat-error>
            <mat-error *ngIf="(form.get('email')).errors?.pattern">Please enter valid email</mat-error>
        </mat-form-field>

        <mat-form-field appearance="standard">
            <mat-label>Address:</mat-label>
            <textarea matInput placeholder="address" formControlName="address"></textarea>
        </mat-form-field>

        <mat-form-field appearance="fill" hintLabel="Country name required">
            <mat-label>Country</mat-label>
            <mat-select matNativeControl name="country" formControlName="country">
                <mat-option value="india">India</mat-option>
                <mat-option value="france">France</mat-option>
                <mat-option value="germany">Germany</mat-option>
                <mat-option value="japan">Japan</mat-option>
                <mat-option value="Mongolia">Mongolia</mat-option>
            </mat-select>
        </mat-form-field>

        <div style="margin-top:10px;">
            <div style="margin-right:3%; color:#6b6b6b;">
                <mat-label>Gender</mat-label>
            </div>
            <mat-radio-group formControlName="gender">
                <mat-radio-button value="Male">Male</mat-radio-button>
                <mat-radio-button value="Female">Female</mat-radio-button>
            </mat-radio-group>
        </div>

        <mat-form-field class="example-full-width" appearance="fill">
            <mat-label>Choose a date</mat-label>
            <input matInput [matDatepicker]="picker" formControlName="dob">
            <mat-datepicker-toggle matSuffix [for]="picker">
                <mat-icon matDatepickerToggleIcon>keyboard_arrow_down</mat-icon>
            </mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
        </mat-form-field>
        <div mat-dialog-actions align="end">
            <button mat-raised-button color="primary" type="submit" [disabled]="!form.valid">Submit</button>
        </div>
    </form>
    <div>{{ form.value | json }}</div>
</div>
Angular material form validatio

How we validate Angular material form

As we are using a reactive form, we can access each individual form element in our template. Angular form control elements have different states like touched, dirty, errors, valid, invalid, untouched, pristine. We can access individual elements using the form.get() method with the name of the individual form control element and then we can check its control status.

We have validated, require minLength and email patterns like this in our template.

<mat-error *ngIf="(form.get('email')).errors?.required">
  Email is required
</mat-error>

<mat-error *ngIf="(form.get('email')).errors?.pattern">
  Please enter valid email
</mat-error>

 <mat-error **ngIf="(form.get('name')).errors?.minlength">
  Please enter more than 10 character
 </mat-error>

How to implement angular material login form ?

We have learned how to configure and use Angular material form components in angular projects. Let now demonstrate an example of an angular material login form. Here is a screenshot of our angular material login form example.

angular material login form

Let edit the app.component.ts file to include reactive form module, form group, and form builder for the angular material login form.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.scss']
})
export class FormComponent implements OnInit {
  form: FormGroup;
  flag: boolean = true;

  constructor(private fb: FormBuilder) { }

  ngOnInit(): void {
    this.form = this.fb.group({
      email: [null, [Validators.required, Validators.pattern("^[a-z0-9._%+-][email protected][a-z0-9.-]+\\.[a-z]{2,4}$")]],
      password: [null, [Validators.required, Validators.minLength(6)]],
    });
  }

  saveDetails(form) {
    alert('SUCCESS!! :-)\n\n' + JSON.stringify(form.value, null, 4));
  }
}

In our component template, we have used another material component called material card, you need to import MatCardModule in our material module. We also have matSuffix, matPrefix attributes to set mat-icon at the end or start. As the name suggests that matPrefix adds an icon at the start of input and matSuffix at end of the input.

We have used visibility on and off to see and make password type text visible or password by toggle flag button. Let edit the app.component.html file.

<mat-card>
    <mat-card-title>Login</mat-card-title>
    <mat-card-content>
        <form [formGroup]="form" (ngSubmit)="saveDetails(form)" autocomplete="off">
            <div>
                <mat-form-field appearance="legacy">
                    <mat-label>Email Address:</mat-label>
                    <input matInput type="email" formControlName="email" placeholder="Your email">
                    <mat-icon matSuffix>mail_outline</mat-icon>
                    <mat-hint>Input the fully qualified email address</mat-hint>
                    <mat-error *ngIf="(form.get('email')).errors?.required">Email is required</mat-error>
                    <mat-error *ngIf="(form.get('email')).errors?.pattern">Please enter valid email</mat-error>
                </mat-form-field>
            </div>

            <div>
                <mat-form-field appearance="standard">
                    <mat-label>Password </mat-label>
                    <input matInput [type]="flag ? 'password' : 'text'" placeholder="Enter your password"
                        formControlName="password">
                    <mat-icon (click)="flag=!flag" matSuffix>{{ flag ? 'visibility' : 'visibility_off' }}</mat-icon>
                    <mat-error>Name is required</mat-error>
                    <mat-error *ngIf="(form.get('password')).errors?.minlength">
                        Please enter more than 6 character
                    </mat-error>
                </mat-form-field>
            </div>

            <div>
                <button mat-raised-button color="primary" type="submit" [disabled]="!form.valid">Login</button>
            </div>

        </form>
    </mat-card-content>
</mat-card>

Like before we have added angular material login form validation, when all login inputs are valid, then we will enable the login button.

Conclusion
We have completed our Angular material form tutorial, we have learned how to use the material form field, Angular material form validation. At last, we have one more example on the Angular material login form to perform password visibility and matPrefix and matSuffix to align icon on input. I hope, you have got some idea.

Related Articles

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top