title: Attribute directive with ngModel to change field value
body: <p>I want to change (force) input field values while typing using a attribute Directive. With it I would like to create directives like uppercase, lowercase, maxlength, filterchar, etc. to be used on input fields on forms. I found this example: <a href="http://www.waynehong.com/javascript/angular-2-attribute-directive-typescript-example/" rel="noreferrer">Angular 2 Attribute Directive Typescript Example</a> but this doesn't seem to work. Maybe it did for an earlier build of Angular2. It is however exactly what I would like to do.</p>
  
  <p>When I create a directive like this:</p>
  
  <pre class="lang-ts prettyprint-override"><code>import {Directive} from 'angular2/core';
  import {NgModel} from 'angular2/common';
  
  @Directive({ 
  selector: '[ngModel][uppercase]', 
  host: {
      '(input)' : 'onInputChange()'
        }
  })
  export class UppercaseDirective{
  
  constructor(public model:NgModel){}
  
  onInputChange(){
      var newValue = this.model.value.toUpperCase();
      this.model.valueAccessor.writeValue(newValue);
      this.model.viewToModelUpdate(newValue);
      }
  }
  </code></pre>
  
  <p>And use it on a form like this:</p>
  
  <pre class="lang-ts prettyprint-override"><code>&lt;input type="text" class="form-control" [(ngModel)]="field.name" ngControl="name" #name="ngForm" required uppercase&gt;
  </code></pre>
  
  <p>(and register <code>NgModel</code> as a provider). I get an </p>
  
  <blockquote>
    <p>undefined this.model.value.</p>
  </blockquote>
  
  <p>I can use <code>$event.target.value = $event.target.value.toUpperCase()</code> (when passing <code>$event</code> with the <code>onInputChange()</code>) and that works for the view (it does show the input as uppercase. But it doesn't update the bind field "field.name".</p>
  
  <p>So how to create an Angular2 attribute directive that does this?</p>
  
  <p><strong>-- EDIT --</strong></p>
  
  <p>After some further investigation I managed to get what I want. The answer Günter provided is closer to my original intention and perhaps better. But here is another way:</p>
  
  <pre class="lang-ts prettyprint-override"><code>import {Directive, Input, Output, EventEmitter} from 'angular2/core';
  
  @Directive({ 
  selector: '[ngModel][uppercase]',
  host: {
  "(input)": 'onInputChange($event)'
      }
  })
  export class UppercaseDirective{
  @Output() ngModelChange:EventEmitter&lt;any&gt; = new EventEmitter()
  value: any
  
  onInputChange($event){
      this.value = $event.target.value.toUpperCase()
      this.ngModelChange.emit(this.value)
      }
  }
  </code></pre>
  
  <p>As I said I'm not sure if this is also a good way to do this so comments are welcome.</p>