首页 文章

屏蔽电话基于角度5的输入字段

提问于
浏览
2

我已经提到了链接:Input mask fields in Angular2 forms并且我能够屏蔽输入字段,如:(123)456-7890 .

请在下面找到更新的代码:

指令TS文件:

@Directive({
  selector: '[appPhoneMasking]',
  host: {
    '(ngModelChange)': 'onInputChange($event)',
    '(keydown.backspace)': 'onInputChange($event.target.value, true)'
  }
})
export class PhoneMaskingDirective {

  constructor(public model: NgControl) {}

  onInputChange(event, backspace) {
    // remove all mask characters (keep only numeric)
    var newVal = event.replace(/\D/g, '');

    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');
    }

    if(newVal.length > 14) {
       newVal = newVal.slice(0, 14); 
    }
    // set the new value
    this.model.valueAccessor.writeValue(newVal);       
  }
}

和HTML文件:

<form [formGroup]="addUser" (ngSubmit)="submitUser()">
     <input type="text" class="form-control" formControlName="user_phone"  appPhoneMasking>
</form>

组件文件:

this.addUser= this._formBuilder.group({
   user_phone: new FormControl('', [Validators.maxLength(14)]),
});

我有两个问题,我试图解决但没有成功 . 这些是:

  • 当我按退格键时,会从字符串中删除两个字符 .

  • 此外,我只想要14个字符在电话号码中 . 只要输入15个字符,输入字段就会更新 . 但表格没有更新 . 我得到的错误是我的表单无效 .

请让我知道如何解决这些问题 .

1 回答

  • 1

    当我按退格键时,会从字符串中删除两个字符 .

    你不需要退格的if,退格事件正在运行,之后你又删除了一个字符 .

相关问题