title: Angular 2 ngModel mutator directive
body: <p>I would like to build a directive that can mutate values being passed to and from an input, bound with ngModel.</p>
  
  <p>Say I wanted to do a date mutation, every time the model changes, the mutator first gets to change the value to the proper format (eg "2017-05-03 00:00:00" is shown as "2017/05/03"), before ngModel updates the view. When the view changes, the mutator gets to change the value before ngModel updates the model (eg entering "2017/08/03" sets the model to "2017-08-03 00:00:00" [timestamp]).</p>
  
  <p>The directive would be used like this:</p>
  
  <pre><code>&lt;input [(ngModel)]="someModel" mutate="date:YYYY/MM/DD" /&gt;
  </code></pre>
  
  <p>My first instinct was to get a reference to the ControlValueAccessor and NgModel on the Host component. </p>
  
  <pre class="lang-js prettyprint-override"><code>import { Directive, ElementRef, Input, 
           Host, OnChanges, Optional, Self, Inject } from '@angular/core';
  import { NgModel, ControlValueAccessor, 
           NG_VALUE_ACCESSOR } from '@angular/forms';
  
  
  @Directive({ 
      selector: '[mutate]',
  })
  export class MutateDirective {
  
      constructor(
          @Host() private _ngModel: NgModel, 
          @Optional() @Self() @Inject(NG_VALUE_ACCESSOR) 
              private _controlValueAccessor: ControlValueAccessor[]
      ){
          console.log('mutute construct', _controlValueAccessor);
      }
  
  
  }
  </code></pre>
  
  <p>Then I realized that the Angular 2 Forms classes are complicated and I have no idea what I'm doing. Any ideas?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>Based on the answer below I came up with the solution: <a href="https://gist.github.com/christiaan-lombard/31c5e3ccbd55f9ce523d64f9bf48b5f5" rel="nofollow noreferrer">see gist</a></p>
  
  <p>Usage (requires Moment JS):</p>
  
  <pre><code>&lt;input  mutate="YYYY/MM/DD" inputFormat="YYYY-MM-DD HH:mm:ss" [(ngModel)]="someDate"&gt;
  </code></pre>