angular - 输入掩码以允许电话号码?

标签 angular forms input

是否有可能在 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:

Plunker >= RC.5

原创

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

Plunker example <= RC.5

关于angular - 输入掩码以允许电话号码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37800841/

相关文章:

css - 如何覆盖 onsen ui 中的 fab 元素 css?

ruby-on-rails - 使用 SimpleForm 为每个选择选项添加一个类

javascript - 在sql和php中插入多个同名的输入文本

javascript 函数 Math.pow 从输入文本中获取十进制值

c# - 如何使用表单提交的绑定(bind)值为 InputText 设置占位符?

angular - 设置混合 AngularJS/Angular 应用程序时出现 "Can' t 解析所有参数错误

ajax - Angular HttpClient 流

android - 获取 ionic 存储中的所有存储 key

ruby-on-rails - 使用带有 accepts_nested_attributes_for 的 Rails 模型

html - jQueryMobile - 表单样式(下拉图标)