是否有可能在 Angular 2 中使用模型驱动的形式并实现一个允许屏蔽 input
字段的指令,例如电话号码条目 (123) 123-4567
?
最佳答案
Angular5 和 6:
angular 5 和 6 推荐的方法是使用@HostBindings 和@HostListeners 而不是主机属性
删除主机并添加@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
Stackblitz 代码示例:https://stackblitz.com/edit/angular6-phone-mask
官方文档链接https://angular.io/guide/attribute-directives#respond-to-user-initiated-events
Angular2 和 4:
原创
一种方法是使用注入(inject) NgControl
并操纵值的指令
(有关详细信息,请参阅内嵌评论)
@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: ['']
})
}
}
关于angular - 输入掩码以允许电话号码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37800841/