angulartypescriptangular-materialangular8

Angular Material: How to validate min and max values on a number field?


I am working on a small project written in Angular 8 and Angular Material.

I have a number field where I want to specify min and max values, however I couldn't find any documentation on how to do that in the matInput documentation.

Question: Does matInput support min/max validations? What is the best way of validation number fields in Angular Material?

So far I tried the standard html5 min and max properties which unfortunately are not caught by the validation engine. I also tried some examples from the internet which turned to be not working in Angular 8.


Solution

  • You can use the reactive approach for creating forms. These might seem to be scary in the first time, but in the end it will be super helpful in setting up different validators.

    Step 1: Import dependencies

    import { ReactiveFormsModule } from '@angular/forms';
    
    @NgModule({
       imports: [
       // other imports ...
       ReactiveFormsModule
       ],
    })
    export class AppModule { }
    

    Step 2: Create a new FormObject

    import { Component } from '@angular/core';
    import { FormGroup, FormControl } from '@angular/forms';
    
    @Component({
      selector: 'app-profile-editor',
      templateUrl: './profile-editor.component.html',
      styleUrls: ['./profile-editor.component.css']
    })
    export class ProfileEditorComponent {
      profileForm = new FormGroup({
        firstName: new FormControl(''),
        lastName: new FormControl(''),
      });
    }
    

    Step 3: Create the template

    <form [formGroup]="profileForm">
    
      <label>
        First Name:
        <input type="text" formControlName="firstName">
      </label>
    
      <label>
        Last Name:
        <input type="text" formControlName="lastName">
      </label>
    
    </form>
    

    Step 4: Add validators

    import { Component } from '@angular/core';
    import { FormGroup, FormControl } from '@angular/forms';
    
    @Component({
      selector: 'app-profile-editor',
      templateUrl: './profile-editor.component.html',
      styleUrls: ['./profile-editor.component.css']
    })
    export class ProfileEditorComponent {
      profileForm = new FormGroup({
        firstName: ['', Validators.required, Validators.min(3)],
        lastName: ['', Validators.required, Validators.min(3)]
      });
    }