首页 > 解决方案 > Mask Directive Not Masking Initial Value

问题描述

I'm attempting to implement some input masks in Angular7 using the instructions found on the accepted answer to this question: Mask For an Input

The code works perfectly when I enter a new value. However, when I initialize the form with a value, the input remains unmasked. I've forked the original question's StackBlitz to show the issue: https://stackblitz.com/edit/angular6-phone-mask-i6aklq

The relevant code from my project is below:

Assigning the values

updateForm(): void {
  this.renewalForm = this.fb.group({
    customFields: this.fb.array(this.license.customFields.map(x => this.fb.control(x.value))),
    contacts: this.fb.array(this.license.contacts.map(x => this.fb.group({
      contactType: new FormControl(x.type),
      contactFirstName: new FormControl(x.firstName),
      contactLastName: new FormControl(x.lastName),
      contactPhone: new FormControl(x.phone), // <---- FormControl being masked
      contactId: new FormControl(x.id)
    })))
  });

  /* I tried assigning the values through setValue, but this didn't work either...
  for (let i = 0; i < this.license.contacts.length; i++) {
    ((this.renewalForm.get("contacts") as FormArray).at(i).get("contactPhone") as FormControl).setValue(this.license.contacts[i].phone);
  }
  */
}

The input HTML

<form [formGroup]="renewalForm" (ngSubmit)="validateForm();">
 <fieldset [disabled]="validated">
  <!-- ... -->
    <mat-form-field>
       <inputplaceholder="Phone Number" formControlName="contactPhone" mask-phone/>
    </mat-form-field>
  <!-- ... -->
 </fieldset >
</form>

The mask directive

import { Directive, HostListener } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
  selector: '[formControlName][mask-phone]',
})
export class MaskPhoneDirective {

  constructor(public ngControl: NgControl) { }

  @HostListener('ngModelChange', ['$event'])
  onModelChange(event) {
    this.onInputChange(event, false);
  }

  @HostListener('keydown.backspace', ['$event'])
  onKeydownBackspace(event) {
    this.onInputChange(event.target.value, true);
  }

  onInputChange(event, backspace) {
    let newVal = event.replace(/\D/g, '');
    if (backspace && newVal.length <= 6) {
      newVal = newVal.substring(0, newVal.length - 1);
    }
    if (newVal.length === 0) {
      newVal = '';
    } 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 if (newVal.length <= 10) {
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) $2-$3');
    } else {
      newVal = newVal.substring(0, 10);
      newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) $2-$3');
    }
    this.ngControl.valueAccessor.writeValue(newVal);
  }
}

Everything works fine, except the masking on the initial value. How can I get the value to mask the initial input?

标签: angular

解决方案


您可以从中提取格式化代码onInputChange,将该代码放入一个formatValue方法中,然后调用该方法ngOnInit来格式化初始值:

ngOnInit() {
  this.formatValue(this.ngControl.value, false);
}  

onInputChange(event, backspace) {
  this.formatValue(event, backspace);
}

formatValue(event, backspace) {
  let newVal = event.replace(/\D/g, '');
  if (backspace && newVal.length <= 6) {
    newVal = newVal.substring(0, newVal.length - 1);
  }
  if (newVal.length === 0) {
    newVal = '';
  } 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 if (newVal.length <= 10) {
    newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) ($2)-$3');
  } else {
    newVal = newVal.substring(0, 10);
    newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, '($1) ($2)-$3');
  }
  this.ngControl.valueAccessor.writeValue(newVal);
}

请参阅此 stackblitz以获取演示。


推荐阅读