以Angular2形式输入掩码字段

前端之家收集整理的这篇文章主要介绍了以Angular2形式输入掩码字段前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有可能在角度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

猜你在找的Angularjs相关文章