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.
Why should I build an exactly same schema with FormControls if I already have all data I need?
Here is my code (https://plnkr.co/edit/fPEdbMihRSVqQ5LZYBHO):
import { Component, Input } from '@angular/core';
export interface MyWidgetModel {
title:string;
description:string;
}
@Component({
selector: 'my-widget',
template: `
<h4 *ngIf="!editing">{{data.title}}</h4>
<input *ngIf="editing" type="text" name="title" [(ngModel)]="data.title">
<p *ngIf="!editing">{{data.description}}</p>
<textarea *ngIf="editing" name="description" [(ngModel)]="data.description" (ngModelChange)="customValidator($event)"></textarea>
<button (click)="clickEditing()">{{editing ? 'save' : 'edit'}}</button>
`
styles: [
':host, :host > * { 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?
}
}
As you can see I can quickly turn on/off editing mode and I can edit my data in-place directly.
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:
- Why should we create a new local variables - with same structure - for FormGroups, FormControls when the data model already exists?
- The component itself implements the required business logic so all business rule validators must be also implemented here.
- 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.
- Because of all above I think we ultimately need our whole component object to solve all real business rule validations.