Angular 输入字段数据格式
Angular input field data format
Angular 模板输入字段应采用 maxLength:mm/dd/yyyy = 10;
<input
class="form-control"
type="text"
appInputMask
formControlName="expiryDate"
id="expiry-date"
maxlength="4"
/>
发现这个指令 appInputMask 可以完成格式 MM/YY 的工作,但我需要 MM/DD/YYYY。
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[formControlName][appInputMask]',
})
export class InputMaskDirective {
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
const trimmed = input.value.replace(/\s+/g, '').slice(0, 4);
if (trimmed.length > 3) {
return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(2)}`);
}
}
}
我正在尝试获得正确的格式,但没有成功,感谢您的帮助。
https://stackblitz.com/edit/angular6-mask-34t827input-6rxqq9?file=app%2Fapp.component.html
首先,在模板中设置 maxLength="8"
。
<input
class="form-control"
type="text"
appInputMask
formControlName="expiryDate"
id="expiry-date"
maxlength="8"
/>
然后像下面这样修改你的指令。
import { Directive, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[formControlName][appInputMask]',
})
export class InputMaskDirective {
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
const trimmed = input.value.replace(/[\s+/]/g, '').slice(0, 8);
if (trimmed.length > 7) {
return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(2, 4)}/${trimmed.slice(4)}`);
} else {
return (input.value = trimmed);
}
}
}
Angular 模板输入字段应采用 maxLength:mm/dd/yyyy = 10;
<input
class="form-control"
type="text"
appInputMask
formControlName="expiryDate"
id="expiry-date"
maxlength="4"
/>
发现这个指令 appInputMask 可以完成格式 MM/YY 的工作,但我需要 MM/DD/YYYY。
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[formControlName][appInputMask]',
})
export class InputMaskDirective {
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
const trimmed = input.value.replace(/\s+/g, '').slice(0, 4);
if (trimmed.length > 3) {
return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(2)}`);
}
}
}
我正在尝试获得正确的格式,但没有成功,感谢您的帮助。
https://stackblitz.com/edit/angular6-mask-34t827input-6rxqq9?file=app%2Fapp.component.html
首先,在模板中设置 maxLength="8"
。
<input
class="form-control"
type="text"
appInputMask
formControlName="expiryDate"
id="expiry-date"
maxlength="8"
/>
然后像下面这样修改你的指令。
import { Directive, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[formControlName][appInputMask]',
})
export class InputMaskDirective {
@HostListener('input', ['$event'])
onKeyDown(event: KeyboardEvent) {
const input = event.target as HTMLInputElement;
const trimmed = input.value.replace(/[\s+/]/g, '').slice(0, 8);
if (trimmed.length > 7) {
return (input.value = `${trimmed.slice(0, 2)}/${trimmed.slice(2, 4)}/${trimmed.slice(4)}`);
} else {
return (input.value = trimmed);
}
}
}