How to add mask on angular material date picker

前端 未结 2 355
深忆病人
深忆病人 2021-01-19 09:07

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.

相关标签:
2条回答
  • 2021-01-19 09:46

    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"

    0 讨论(0)
  • 2021-01-19 09:49

    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);
        });
    
    0 讨论(0)
提交回复
热议问题