-
-
Save Trend20/0cf194fe6151e45e679b1e8f1a801bea to your computer and use it in GitHub Desktop.
Using text-mask with Material datepicker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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