允许输入电话号码的输入掩码?

编程入门 行业动态 更新时间:2024-10-12 01:25:13
本文介绍了允许输入电话号码的输入掩码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否有可能在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链接: angular6-phone-mask.stackblitz.io

Working Online stackblitz Link: angular6-phone-mask.stackblitz.io

Stackblitz代码示例: stackblitz/edit/angular6-phone-mask

Stackblitz Code example: stackblitz/edit/angular6-phone-mask

官方文档链接 angrefer.io/guide/attribute-directives#respond-to-user-initiated-events

Angular2和4:

柱塞> = RC.5

原始

一种实现方法是使用注入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: [''] }) } }

> 柱塞示例< = RC.5

更多推荐

允许输入电话号码的输入掩码?

本文发布于:2023-11-13 04:24:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583419.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:电话号码   掩码

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!