title: Angular2 ngModel validator just in the component
body: <p>I try to figure out the simplest way to implement a custom validator logic for ngModel. I have a pre-defined model (interface) which stores current data so I don't want to deal with the new FormGroup/FormControl (model-driven) approach. </p>
  
  <p><em>Why should I build an exactly same schema with FormControls if I already have all data I need?</em></p>
  
  <p>Here is my code (<a href="https://plnkr.co/edit/fPEdbMihRSVqQ5LZYBHO" rel="noreferrer">https://plnkr.co/edit/fPEdbMihRSVqQ5LZYBHO</a>):</p>
  
  <pre><code>import { Component, Input } from '@angular/core';
  
  
  export interface MyWidgetModel {
    title:string;
    description:string;
  }
  
  
  @Component({
    selector: 'my-widget',
    template: `
      &lt;h4 *ngIf="!editing"&gt;{{data.title}}&lt;/h4&gt;
      &lt;input *ngIf="editing" type="text" name="title" [(ngModel)]="data.title"&gt;
  
      &lt;p *ngIf="!editing"&gt;{{data.description}}&lt;/p&gt;
      &lt;textarea *ngIf="editing" name="description" [(ngModel)]="data.description" (ngModelChange)="customValidator($event)"&gt;&lt;/textarea&gt;
  
      &lt;button (click)="clickEditing()"&gt;{{editing ? 'save' : 'edit'}}&lt;/button&gt;
  
    `
    styles: [
      ':host, :host &gt; * { display: block; margin: 5px; }',
      ':host { margin-bottom: 10px; padding-bottom: 10px; border-bottom: 1px solid #eee; }',
      '.ng-invalid { background-color: #FEE; }'
    ]
  
  })
  export class MyWidgetComponent {
    @Input() data:MyWidgetModel;
  
    constructor() {
      this.editing = false;
    }
  
    clickEditing() {
      this.editing = !this.editing;
    }
  
    customValidator(value:string) {
      console.log(this, value); //should be: MyWidgetComponent
      //How to set 'invalid' state here?
    }
  
  }
  </code></pre>
  
  <p>As you can see I can quickly turn on/off editing mode and I can edit my data in-place directly. </p>
  
  <p>My question is how to manage ng-valid/ng-invalid states of the ngModel directly from my component? The idea behind this consists multiple points:</p>
  
  <ul>
  <li>Why should we create a new local variables - with same structure - for FormGroups, FormControls when the data model already exists?</li>
  <li>The component itself implements the required business logic so all business rule validators must be also implemented here.</li>
  <li>There can be many complicated validation logics. These cannot be implemented just using the pure text values of inputs and simple checks like required, length, pattern etc.</li>
  <li>Because of all above I think we ultimately need our whole component object to solve all real business rule validations. </li>
  </ul>