Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Driven Forms in Angular 2

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.)

like image 757
Thomas Avatar asked Jan 20 '16 14:01

Thomas


1 Answers

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

like image 125
Olegas Gončarovas Avatar answered Oct 13 '22 13:10

Olegas Gončarovas