Skip to content

Instantly share code, notes, and snippets.

@AntonGorelov
Last active January 9, 2023 13:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AntonGorelov/82dab44949353fee2da22a697da77157 to your computer and use it in GitHub Desktop.
Save AntonGorelov/82dab44949353fee2da22a697da77157 to your computer and use it in GitHub Desktop.
Using text-mask with Material datepicker
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 {
public mask = [/\d/, /\d/, '/', /\d/, /\d/, '/', /\d/, /\d/, /\d/, /\d/]; // dd/mm/yyyy
public maskedInputController;
constructor(private element: ElementRef) {
this.maskedInputController = textMask.maskInput({
inputElement: this.element.nativeElement,
mask: this.mask
});
}
public ngOnDestroy(): void {
this.maskedInputController.destroy();
}
}
<mat-form-field>
<mat-placeholder>Enter Ends Date</mat-placeholder>
<mat-datepicker-toggle matSuffix [for]="datePicker"></mat-datepicker-toggle>
<mat-datepicker #datePicker></mat-datepicker>
<input matInput
formControlName="dateEnd"
[matDatepicker]="datePicker"
#dateEnd
appMaskDate
required>
<mat-error *ngIf="dateEndCtrl.hasError('dateStartEndRange')">
{{ tForm.endDate.validation.dateTimeLimit | translate }}
</mat-error>
</mat-form-field>
public eventSubscription: Subscription;
@ViewChild('dateEnd')
public dateEnd: ElementRef;
@ViewChild(MatDatepickerInput)
public datepickerInput: MatDatepickerInput<any>;
public ngAfterViewInit() {
this.eventSubscription = fromEvent(this.dateEnd.nativeElement, 'input')
.pipe(takeUntil(this._destroyed))
.subscribe(() => {
this.datepickerInput._onInput(this.dateEnd.nativeElement.value);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment