title: Phone mask directive in Angular 8
body: <p>I have this phone mask directive which accepts a phone number in US format. However, when i clear the contents in the input by hitting backspace one by one, the value inside the input form is not being emptied. I didn't realize this issue until I logged the input value of the form.</p>
  <p>And, when I clear the input form at once, it is being emptied. But, clearing by form value one by one hitting the backspace always leaves one value.</p>
  <p><a href="https://i.stack.imgur.com/Tg6HMm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Tg6HMm.png" alt="input-form-value" /></a></p>
  <p>How do I clear the input value when the form value is empty?</p>
  <p>I created a working example using <a href="https://stackblitz.com/edit/angular6-phone-mask-gao3fk?file=app%2Fphone-mask.directive.ts" rel="nofollow noreferrer">StackBlitz</a>. Could anyone please help?</p>
  <p><strong>Directive</strong></p>
  <pre><code>export class PhoneMaskDirective {
    constructor(public ngControl: NgControl) {}
  
    @HostListener(&quot;ngModelChange&quot;, [&quot;$event&quot;])
    onModelChange(event) {
      this.onInputChange(event, false);
    }
  
    @HostListener(&quot;keydown.backspace&quot;, [&quot;$event&quot;])
    keydownBackspace(event) {
      this.onInputChange(event.target.value, true);
    }
  
    onInputChange(event, backspace) {
      if (event == null) {
        return &quot;&quot;;
      }
      let newVal = event.replace(/\D/g, &quot;&quot;);
  
      if (backspace &amp;&amp; newVal.length &lt;= 6) {
        newVal = newVal.substring(0, newVal.length - 1);
      }
      if (newVal.length === 0) {
        newVal = &quot;&quot;;
      } else if (newVal.length &lt;= 3) {
        newVal = newVal.replace(/^(\d{0,3})/, &quot;($1)&quot;);
      } else if (newVal.length &lt;= 6) {
        newVal = newVal.replace(/^(\d{0,3})(\d{0,3})/, &quot;($1) $2&quot;);
      } else if (newVal.length &lt;= 10) {
        newVal = newVal.replace(/^(\d{0,3})(\d{0,3})(\d{0,4})/, &quot;($1) $2-$3&quot;);
      }
      this.ngControl.valueAccessor.writeValue(newVal);
    }
  }
  
  </code></pre>