允许输入电话号码的输入掩码? [英] Mask for an Input to allow phone numbers?
问题描述
是否有可能在Angular 2中具有模型驱动的形式并实现一条指令,该指令将允许屏蔽input
字段,例如电话号码条目(123) 123-4567
?
Is it possible to have model-driven form in Angular 2 and implement a directive that would allow to mask an input
field like a phone number entry (123) 123-4567
?
推荐答案
Angular5和6:
推荐的角度5和6的方法是使用@HostBindings和@HostListeners代替host属性
angular 5 and 6 recommended way is to use @HostBindings and @HostListeners instead of the host property
删除主机并添加 @HostListener
@HostListener('ngModelChange', ['$event'])
onModelChange(event) {
this.onInputChange(event, false);
}
@HostListener('keydown.backspace', ['$event'])
keydownBackspace(event) {
this.onInputChange(event.target.value, true);
}
在线工作stackblitz链接: https://angular6-phone-mask.stackblitz.io
Working Online stackblitz Link: https://angular6-phone-mask.stackblitz.io
Stackblitz代码示例: https://stackblitz.com/edit/angular6-phone-mask
Stackblitz Code example: https://stackblitz.com/edit/angular6-phone-mask
官方文档链接 https://angrefer.io/guide/attribute-directives#respond-to-user-initiated-events
Angular2和4:
原始
一种实现方法是使用注入NgControl
并处理值的指令
One way you could do it is using a directive that injects NgControl
and manipulates the value
(有关详细信息,请参见嵌入式注释)
@Directive({
selector: '[ngModel][phone]',
host: {
'(ngModelChange)': 'onInputChange($event)',
'(keydown.backspace)': 'onInputChange($event.target.value, true)'
}
})
export class PhoneMask {
constructor(public model: NgControl) {}
onInputChange(event, backspace) {
// remove all mask characters (keep only numeric)
var newVal = event.replace(/\D/g, '');
// special handling of backspace necessary otherwise
// deleting of non-numeric characters is not recognized
// this laves room for improvement for example if you delete in the
// middle of the string
if (backspace) {
newVal = newVal.substring(0, newVal.length - 1);
}
// don't show braces for empty value
if (newVal.length == 0) {
newVal = '';
}
// don't show braces for empty groups at the end
else if (newVal.length <= 3) {
newVal = newVal.replace(/^(\d{0,3})/, '($1)');
} else if (newVal.length <= 6) {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, '($1) ($2)');
} else {
newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(.*)/, '($1) ($2)-$3');
}
// set the new value
this.model.valueAccessor.writeValue(newVal);
}
}
@Component({
selector: 'my-app',
providers: [],
template: `
<form [ngFormModel]="form">
<input type="text" phone [(ngModel)]="data" ngControl="phone">
</form>
`,
directives: [PhoneMask]
})
export class App {
constructor(fb: FormBuilder) {
this.form = fb.group({
phone: ['']
})
}
}
这篇关于允许输入电话号码的输入掩码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!