加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

以Angular2形式输入掩码字段

发布时间:2020-12-17 07:45:35 所属栏目:安全 来源:网络整理
导读:有可能在角度2中有模型驱动形式,并找到可以屏蔽输入字段(如电话号码输入)的指令 (123)123-4567? Plunker = RC.5 原版的 您可以使用一种方法来使用注入NgControl并操纵该值的指令 (详情请参阅内线评论) @Directive({ selector: '[ngModel][phone]',host: { '
有可能在角度2中有模型驱动形式,并找到可以屏蔽输入字段(如电话号码输入)的指令
(123)123-4567?
Plunker >= RC.5

原版的

您可以使用一种方法来使用注入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,'($1) ($2)');
    } else {
      newVal = newVal.replace(/^(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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读