簡體   English   中英

如何將掩碼應用於打字稿中的默認值

[英]How to apply mask to a default value in Typescript

我有一個 mask-phone 指令,當用戶寫一個值時,它在輸入中完美地工作,但我需要設置一個默認值,我不知道如何在組件方法中應用 mask 指令。 該值顯示在沒有掩碼的輸入中,只有當我修改該值時,掩碼才會出現。

我遇到的問題是,在德國,電話號碼有多種可能,因此我無法在默認值中設置特定掩碼,例如:(49)(170)-1111111 (49)(1514)-1111111 (49 )(25679)-1111111

我寫了一個例子,你可以在以下鏈接中看到: https : //stackblitz.com/edit/angular5-phone-mask-directive-roeqfk?file=app/app.component.ts

提前致謝 :)

您可以從指令內部提供默認值並在OnInit生命周期掛鈎中設置掩碼。 這還有一個好處,即每次使用此指令時默認值都相同。

代碼:

import {Directive, ElementRef, HostListener, OnInit} from '@angular/core';
import {NgControl} from '@angular/forms';
@Directive({
  selector: '[formControlName][appPhoneMask]'
})
export class PhoneMaskDirective implements OnInit{
  defaultValue: string = '4912345678'

  constructor(public ngControl: NgControl, private elementRef: ElementRef) { }

  ngOnInit(): void {
    this.applyMask(this.defaultValue)
  }

  @HostListener('ngModelChange', ['$event'])
  onModelChange(event): void {
    this.onInputChange(event, false);
  }
  @HostListener('keydown.backspace', ['$event'])
  keydownBackspace(event): void {
    this.onInputChange(event.target.value, true);
  }
  onInputChange(event, backspace): void {
    let newVal = event.replace(/\D/g, '');
    if (backspace && newVal.length <= 6) {
      newVal = newVal.substring(0, newVal.length - 1);
    }
    
    this.applyMask(newVal)
  }

  applyMask (value): void {
    if (value.length === 0) {
      value = '';
    } else if (value.length <= 3) {
      value = value.replace(/^(\d{0,2})/, '($1)');
    } else if (value.length <= 6) {
      value = value.replace(/^(\d{0,2})(\d{0,3})/, '($1) ($2)');
    } else if (value.length <= 12) {
      value = value.replace(/^(\d{0,2})(\d{0,3})(\d{0,7})/, '($1) ($2)-$3');
    } else if (value.length <= 13) {
      value = value.replace(/^(\d{0,2})(\d{0,4})(\d{0,7})/, '($1) ($2)-$3');
    } else if (value.length <= 14) {
      value = value.replace(/^(\d{0,2})(\d{0,5})(\d{0,7})/, '($1) ($2)-$3');
    } else {
      value = value.substring(0, 14);
      value = value.replace(/^(\d{0,2})(\d{0,5})(\d{0,7})/, '($1) ($2)-$3');
    }
    this.ngControl.valueAccessor.writeValue(value);
  }

  /** This method allows to keep the formControl value without the mask, in order to use it in backend queries */
  @HostListener('input') onChange(): void {
    const newVal = this.elementRef.nativeElement.value.replace(/\D/g, '');
    this.ngControl.control.setValue(newVal, {
      emitEvent: false,
      emitModelToViewChange: false,
      emitViewToModelChange: false
    });
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM