ivanka naceva
ivanka naceva

Reputation: 93

How to add mask on angular material date picker

I recently started using angular material to build angular form in which i need to use angular material date picker but am not able to add any mask on the input element.

I want to allow the user only to be able to enter numbers and to format them in date format (MM/DD/YYYY) as he types in.

html:

<div class="example-container">
  <mat-form-field appearance="outline" class="col-sm-12 col-md-6 col-lg-6 required margin-top-ten">
    <mat-label>
      <span class="title">Date of Birth (MM/DD/YYYY)</span>  
    </mat-label>
    <input matInput [matDatepicker]="myDatepicker" formControlName="dateOfBirth" maxlength="10">
    <mat-datepicker-toggle matSuffix [for]="myDatepicker"></mat-datepicker-toggle>
    <mat-datepicker #myDatepicker></mat-datepicker>  
  </mat-form-field>
</div>

Note: I was trying to use ngx-mask and is not working on date picker only, on a regular text input like phone or fax fields is working just fine.

Upvotes: 5

Views: 13330

Answers (2)

Иии Лее
Иии Лее

Reputation: 127

Create directive

import { Directive, ElementRef, OnDestroy } from '@angular/core';
import * as textMask from 'vanilla-text-mask/dist/vanillaTextMask.js';

@Directive({
  selector: '[appMaskDate]'
})
export class MaskDateDirective implements OnDestroy {

  mask = [/\d/, /\d/, '/', /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/]; // dd/mm/yyyy
  maskedInputController;

  constructor(private element: ElementRef) {
    this.maskedInputController = textMask.maskInput({
      inputElement: this.element.nativeElement,
      mask: this.mask
    });
  }

  ngOnDestroy() {
    this.maskedInputController.destroy();
  }

}

use mask selector for the datepicker input

  <input matInput [matDatepicker]="dateOfBirth" #dateOfBirth appMaskDate>

Add subscription to the material datepicker own input

  eventSubscription: Subscription;
  @ViewChild('dateOfBirth') dateOfBirth: ElementRef;
  @ViewChild(MatDatepickerInput) datepickerInput: MatDatepickerInput<any>; 

and on ngAfterViewInit

   this.eventSubscription = fromEvent(this.dateOfBirth.nativeElement, 'input').subscribe(_ => {
      this.datepickerInput._onInput(this.dateOfBirth.nativeElement.value);
    });

Upvotes: 5

Code_maniac
Code_maniac

Reputation: 278

Check out the documentation below for sample use of datepicker. https://www.npmjs.com/package/angular4-datepicker

  1. Add a variable in the component

    myDatePickerOptions: IMyDpOptions = {
        // other options...
    dateFormat: 'dd.mm.yyyy'
    };
    
  2. assign it to the input element.

    [options]="myDatePickerOptions"

Upvotes: -3

Related Questions