Angular Material Form Controls, Form Field and Input Examples

by Didin J. on Oct 28, 2019 Angular Material Form Controls, Form Field and Input Examples

The series of a comprehensive step by step Angular Material components (Form Controls, Form Field, and Input) tutorial complete with the working examples

In this Angular Material series, we will show you how to use Angular Material Form Controls, Form Field, and Input with the working examples. An angular Material Form control is an essential component, especially when working with the data. There are some Angular Material Form Controls like autocomplete, checkbox, date picker, form field, input, radio button, select, slider, and slide toggle. This time we will show you examples for all of Angular Material Form Controls, Form Field, and Input.

Table of Contents:

The following tools, frameworks, and libraries or modules are required for this tutorial.

  1. Node.js
  2. Angular 8
  3. Angular Material
  4. Terminal (Linux/Mac) or Node Command Line (Windows)
  5. Text Editor or IDE (We use VSCode)


Preparation

We will bundle all of this Angular Material Form Controls examples in one application. For that, we will prepare all required Angular 8 applications and Angular Material. Now, we are creating an Angular 8 app using Angular CLI which needs Node.js and NPM to install or update it. Make sure you have to install Node.js and NPM before installing or updating Angular CLI. To install or update an Angular CLI type this command.

sudo npm install -g @angular/cli

Next, create a new Angular 8 app using Angular CLI by type this command.

ng new angular-material-form-controls

That command will create a new Angular 8 app with the name `angular-material-form-controls` and pass all questions as 'Y' then the Angular CLI will automatically install the required NPM modules. After finished, go to the newly created Angular 8 folder then run the Angular 8 app for the first time.

cd ./angular-material-form-controls
ng serve --open

Using that "--open" parameters will automatically open the Angular 8 in your default web browser. Here's the Angular 8 default page look like.

https://s3-ap-southeast-1.amazonaws.com/djamblog/article-181019205345.png

Next, type this command to install Angular Material using Angular CLI's install schematics.

ng add @angular/material

Leave all questions as default to finish the installation.

? Choose a prebuilt theme name, or "custom" for a custom theme: Indigo/Pink        [ Preview: https://mate
rial.angular.io?theme=indigo-pink ]
? Set up HammerJS for gesture recognition? Yes
? Set up browser animations for Angular Material? Yes

Next, open the Angular application project with your text editor or IDE. Open and edit `src/app/app.module.ts` then add these required imports of @angular/forms FormsModule, ReactiveFormsModule, @angular/material MatInputModule, and MatFormFieldModule.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';

Register the above modules to `@NgModule` imports.

imports: [
  BrowserModule,
  AppRoutingModule,
  BrowserAnimationsModule,
  FormsModule,
  ReactiveFormsModule,
  MatInputModule,
  MatFormFieldModule
],

Now, the Angular Material Form Controls Components and Angular Reactive Form modules are ready to use in Angular Components.


Form Field Examples

The Angular Material Form Field is the wrapper for the other form controls elements such as input, text-area, select, radio button, checkbox, etc. Also, advanced the style for the components that wrapped by this Form field. The Angular Material Form Field using <mat-form-field> tag.

Basic Form Fields

This example show you a basic form fields usage that wrap input, textarea, and select components. We can use `src/app/app.component.html` then replace the content of <div class="content" role="main"> element.

<div class="form-container">
  <mat-form-field>
    <input matInput placeholder="Input">
  </mat-form-field>

  <mat-form-field>
    <textarea matInput placeholder="Textarea"></textarea>
  </mat-form-field>

  <mat-form-field>
    <mat-select placeholder="Select">
      <mat-option value="option">Option</mat-option>
    </mat-select>
  </mat-form-field>
</div>

Add this styles on `src/app/app.component.scss`.

.form-container {
  display: flex;
  flex-direction: column;
}

.form-container > * {
  width: 100%;
}

Form Field with Appearance Property Example

This example will show you the Form field appearance property usage. You can comment out the previous example and add these HTML tags in `src/app/app.component.html`.

<!-- Legacy form field -->
<p>
  <mat-form-field appearance="legacy">
    <mat-label>Email Address:</mat-label>
    <input matInput placeholder="Your email">
    <mat-icon matSuffix>mail_outline</mat-icon>
    <mat-hint>Input the fully qualified email address</mat-hint>
  </mat-form-field>
</p>
<!-- Standard form field -->
<p>
  <mat-form-field appearance="standard">
    <mat-label>Phone Number:</mat-label>
    <input matInput placeholder="Your Phone">
    <mat-icon matSuffix>phone</mat-icon>
    <mat-hint>Phone number with Country code</mat-hint>
  </mat-form-field>
</p>
<!-- Fill form field -->
<p>
  <mat-form-field appearance="fill">
    <mat-label>Username:</mat-label>
    <input matInput placeholder="Your username">
    <mat-icon matSuffix>person_outline</mat-icon>
    <mat-hint>Use unique username</mat-hint>
  </mat-form-field>
</p>
<!-- Outline form field -->
<p>
  <mat-form-field appearance="outline">
    <mat-label>Password</mat-label>
    <input matInput placeholder="Your password">
    <mat-icon matSuffix>lock</mat-icon>
    <mat-hint>Min 8 char 1 number and 1 alpha</mat-hint>
  </mat-form-field>
</p>

Floating Label and Hide Required Marker

There are properties in <mat-form-field> to configure floating label mode and hide required marker (asterix). Here the examples for them.

<!-- Hide required marker (asterix) and auto float label -->
<mat-form-field [hideRequiredMarker]="true" [floatLabel]="'auto'">
  <input matInput placeholder="First Name" required>
</mat-form-field>

<!-- Show required marked (asterix) and auto float label -->
<mat-form-field [floatLabel]="'auto'">
  <mat-label>Last Name</mat-label>
  <input matInput placeholder="Last Name" required>
</mat-form-field>

<!-- Always float label -->
<mat-form-field [floatLabel]="'always'">
  <mat-label>Nickname</mat-label>
  <input matInput placeholder="Nickname">
</mat-form-field>

<!-- Disable float label -->
<mat-form-field [floatLabel]="'never'">
  <mat-label>Family Name</mat-label>
  <input matInput placeholder="Family Name">
</mat-form-field>

To configure float label globally you can add this import of MAT_LABEL_GLOBAL_OPTIONS in `src/app/app.module.ts`.

import { MAT_LABEL_GLOBAL_OPTIONS } from '@angular/material/core';

Add it to @NgModule providers.

providers: [
  { provide: MAT_LABEL_GLOBAL_OPTIONS, useValue: {float: 'always'} }
],

Remove all [floatLabel] property in each <mat-form-field> that will use global configuration.

Show Hint Labels

This is an example of hint labels using <mat-hint> component that display hint in <mat-form-field> with specific position left and right using align attribute.

<mat-form-field hintLabel="Min 6 and Max 10 characters">
  <input matInput #input minLength="6" maxlength="20" placeholder="Enter Your Username">
  <mat-hint align="end">Estimate: {{(20 - input.value?.length) || 20}}</mat-hint>
</mat-form-field>

<mat-form-field>
  <input matInput placeholder="Enter Your Email">
  <mat-hint align="end">Fill with the valid email ^</mat-hint>
</mat-form-field>

Show Error Messages

This example will show you how to display an error message if something wrong while type or fill the input. The error messages will be displayed below the input and will be hidden as default if there are no errors caught. This example will use Angular FormControl validator, for that, open and edit `src/app/app.component.ts` then add this import.

import { FormControl, Validators } from '@angular/forms';

Add a variable of the FormControl and the validator.

email = new FormControl('', [Validators.required, Validators.email]);

Add a function to display the error messages.

getErrorMessage() {
  return this.email.hasError('required') ? 'You must enter a value' :
      this.email.hasError('email') ? 'Not a valid email' :
          '';
}

Back to the HTML, commenting on the previous example and add this example of error messages.

<mat-form-field>
  <input matInput placeholder="Enter your email" [formControl]="email" required>
  <mat-error *ngIf="email.invalid">{{getErrorMessage()}}</mat-error>
</mat-form-field>

Prefix/Suffix or Before/After Label

The Form Field can show labels before and after the input. Prefix or before using matPrefix attribute and Suffix or after using matSuffix. Here's the example.

<mat-form-field>
  <input matInput placeholder="Price" type="number" class="example-right-align">
  <span matPrefix>Rp.</span>
  <span matSuffix>.00</span>
</mat-form-field>

Styling the Form Field

The <mat-form-field> style can override or change by change the styles of mat-form-field and .mat-form-field. To override it, open and edit `src/app/app.component.scss` then add this styles.

mat-form-field.mat-form-field {
  font-size: 16px;
  color: blue;
  background-color: burlywood;
  border: solid 1px #c0c0ff;
}


Input Examples

The Angular Material input or text-area marked by matInput that added to standard HTML input and text-area. That will make the HTML input and text-area works inside <mat-form-field>.

Basic Input and TextArea Example

This example is basic usage of Angular Material matInput inside HTML input and textarea which wrapped by <mat-form-field>.

<mat-form-field class="example-full-width">
  <input matInput placeholder="Article Title" value="The Angular 8 Material">
</mat-form-field>

<mat-form-field class="example-full-width">
  <textarea matInput placeholder="Article Description"></textarea>
</mat-form-field>

Supported Input Types Example

This example is the supported types for input mapInput like text, color, date, datetime-local, email, month, number, password, search, tel, time, url, and week.

<!-- Text -->
<mat-form-field class="example-full-width">
  <input matInput type="text" placeholder="Article Title" value="The Angular 8 Material">
</mat-form-field>
<!-- Color -->
<mat-form-field class="example-full-width">
  <input matInput type="color" placeholder="Choose Your Color">
</mat-form-field>
<!-- Date -->
<mat-form-field class="example-full-width">
  <input matInput type="date" placeholder="Published Date">
</mat-form-field>
<!-- Datetime-Local -->
<mat-form-field class="example-full-width">
  <input matInput type="datetime-local" placeholder="Published Date (Local)">
</mat-form-field>
<!-- Email -->
<mat-form-field class="example-full-width">
  <input matInput type="email" placeholder="Your Email Address">
</mat-form-field>
<!-- Month -->
<mat-form-field class="example-full-width">
  <input matInput type="month" placeholder="Published Month">
</mat-form-field>
<!-- Number -->
<mat-form-field class="example-full-width">
  <input matInput type="number" placeholder="Price">
</mat-form-field>
<!-- Password -->
<mat-form-field class="example-full-width">
  <input matInput type="password" placeholder="Enter Your Password">
</mat-form-field>
<!-- Search -->
<mat-form-field class="example-full-width">
  <input matInput type="search" placeholder="Find here">
</mat-form-field>
<!-- Phone Number -->
<mat-form-field class="example-full-width">
  <input matInput type="tel" placeholder="Your Phone Number">
</mat-form-field>
<!-- Time -->
<mat-form-field class="example-full-width">
  <input matInput type="time" placeholder="Release Time">
</mat-form-field>
<!-- URL -->
<mat-form-field class="example-full-width">
  <input matInput type="url" placeholder="Your Website">
</mat-form-field>
<!-- Week -->
<mat-form-field class="example-full-width">
  <input matInput type="week" placeholder="Release Week">
</mat-form-field>


Input with a custom ErrorStateMatcher

Failure input usage can throw an error that display at the bottom of the input using custom ErrorStateMatcher. The use of error message is allowed by <mat-form-field>. To use ErrorStateMatcher, add/modify these imports to the `src/app/app.component.ts`.

import { FormControl, FormGroupDirective, NgForm, Validators } from '@angular/forms';
import { ErrorStateMatcher } from '@angular/material/core';

Add this class of ErrorStateMatcher before the main @Component.

/** Error when invalid control is dirty, touched, or submitted. */
export class MyErrorStateMatcher implements ErrorStateMatcher {
  isErrorState(control: FormControl | null, form: FormGroupDirective | NgForm | null): boolean {
    const isSubmitted = form && form.submitted;
    return !!(control && control.invalid && (control.dirty || control.touched || isSubmitted));
  }
}

Add this FormControl validator and instantiate ErrorStateMatcher inside AppComponent bracket.

emailFormControl = new FormControl('', [
  Validators.required,
  Validators.email,
]);

matcher = new MyErrorStateMatcher();

Back to `src/app/app.component.html` then add this example of ErrorStateMatcher usage.

<mat-form-field class="example-full-width">
  <input matInput placeholder="Email Address" [formControl]="emailFormControl"
         [errorStateMatcher]="matcher">
  <mat-hint>Errors appear instantly!</mat-hint>
  <mat-error *ngIf="emailFormControl.hasError('email') && !emailFormControl.hasError('required')">
    Please enter a valid email address
  </mat-error>
  <mat-error *ngIf="emailFormControl.hasError('required')">
    Email is <strong>required</strong>
  </mat-error>
</mat-form-field>


That it's, the example of Angular Material Form Controls, Form Field, and Input. As usual, you can get full source codes in our GitHub.

If you don’t want to waste your time design your own front-end or your budget to spend by hiring a web designer then Angular Templates is the best place to go. So, speed up your front-end web development with premium Angular templates. Choose your template for your front-end project here.

That just the basic. If you need more deep learning about MEAN Stack, Angular, and Node.js, you can take the following cheap course:

Thanks!