如何在有角材质的日期选择器上添加蒙版 [英] 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.
我只允许用户输入数字并在输入时以日期格式(MM/DD/YYYY)格式化它们.
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>
注意: 我试图使用 ngx-mask ,而不仅在日期选择器上工作,在电话或传真字段之类的常规文本输入上也能正常工作.
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.
推荐答案
创建指令
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>;
以及ngAfterViewInit上
and on ngAfterViewInit
this.eventSubscription = fromEvent(this.dateOfBirth.nativeElement, 'input').subscribe(_ => {
this.datepickerInput._onInput(this.dateOfBirth.nativeElement.value);
});
这篇关于如何在有角材质的日期选择器上添加蒙版的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!