Looking at the advantages and disadvantages of Template Driven vs. Model Driven Forms in Angular 2 (beta.0), I'm wondering how a custom validation can be attached to a simple text input field using Template Driven Forms. There are no examples (beside required) available for this approach or I did not find them.
<form #f="ngForm">
<label for="name">Name</label>
<input type="text" ngControl="name" [(ngModel)]="obj.name" #name="ngForm">
<button type="button" (click)="save()">Save</button>
</form>
As an example validation function:
validate(control:Control):ValidationResult {
if (control.value === 'Monkey') {
return { invalidName: true }
}
}
The above validation function works using in a Model Driven Form using FormBuilder. How could this be done using the Template Driven approach?
An answer like "It's not possible and won't be in the future too." or "It's not best practise, go with the Model Driven approach." together with an argument will be more than fine with me. (I already assume that there is no way but find no evidence in the web and I prefer the Model Driven approach more.)
In template driven forms you need to create a directive for custom validator and append it to the input element like html attribute (the same way as you would append required
attribute).
You should read this article on how to create directives for custom validators: http://blog.thoughtram.io/angular/2016/03/14/custom-validators-in-angular-2.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With