Search code examples
angularangular2-forms

How can I dynamically format an input element in angular2?


I am using angular2, the new forms api.

I want to have a phone number input box, which is auto-formatted as the user types.

For example the user types:

12345678901

and as they enter a recognizable phone number it changes to

1 (234) 567-8901

I figured out how to add a directive onto the input control but I don't know how to inject myself into the input processing pipeline.


Solution

  • You have to create your own directive, take this one as an example, it transforms using Phone.format, storing the raw number in the model but displaying the formatted number to the user:

    import { Directive } from '@angular/core'
    import { NgControl } from '@angular/forms'
    import { Phone } from '../phone'
    
    @Directive({
      selector: '[ngModel][phone]',
      host: {
        '(ngModelChange)': 'onInputChange($event)',
        '(blur)': 'onBlur($event)'
      }
    })
    export class PhoneDirective {
    
      constructor (control: NgControl) {
        this.control = control
      }
    
      ngOnInit () {
        let formatted = Phone.format(this.control.model)
        setTimeout(() => this.control.valueAccessor.writeValue(formatted), 0)
      }
    
      onBlur () {
        let val = this.control.model
        let raw = val.replace(/\W/g, '')
        let formatted = Phone.format(raw)
    
        this.control.valueAccessor.writeValue(formatted)
        this.control.viewToModelUpdate(raw)
      }
    
      onInputChange (val) {
        let raw = val.replace(/\W/g, '')
        if (val !== raw) this.control.viewToModelUpdate(raw)
      }
    }