6

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

Thomas
  • 8,357
  • 15
  • 45
  • 81
  • 1
    See if this helps: http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/ – Langley Jan 20 '16 at 16:05
  • 1
    have a look here... http://stackoverflow.com/q/34350049/5043867 – Pardeep Jain Jan 20 '16 at 16:09
  • Unfortunately there are just examples using FormBuilder. Im wondering if I can attach a validator when I am going to define `ngControl="name"` implicitly? – Thomas Jan 21 '16 at 16:16

3 Answers3

2

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

Olegas Gončarovas
  • 1,521
  • 1
  • 11
  • 16
0

In Template driven froms you have to create directive for custom validator and use it to template elements.

here is my directive file,

validator.directive.ts

import { Directive, forwardRef, Attribute } from '@angular/core';
import { Validator, AbstractControl, NG_VALIDATORS } from '@angular/forms';

@Directive({
    selector: '[validateEqual][formControlName],[validateEqual][formControl],[validateEqual][ngModel]',
    providers: [
        { provide: NG_VALIDATORS, useExisting: forwardRef(() => EqualValidator), multi: true }
    ]
})
export class EqualValidator implements Validator {
    constructor( @Attribute('validateEqual') public validateEqual: string,
        @Attribute('reverse') public reverse: string) {

    }

    private get isReverse() {
        if (!this.reverse) return false;
        return this.reverse === 'true' ? true: false;
    }

    validate(c: AbstractControl): { [key: string]: any } {
        // self value
        let v = c.value;

        // control vlaue
        let e = c.root.get(this.validateEqual);

        // value not equal
        if (e && v !== e.value && !this.isReverse) {
          return {
            validateEqual: false
          }
        }

        // value equal and reverse
        if (e && v === e.value && this.isReverse) {
            delete e.errors['validateEqual'];
            if (!Object.keys(e.errors).length) e.setErrors(null);
        }

        // value not equal and reverse
        if (e && v !== e.value && this.isReverse) {
            e.setErrors({
                validateEqual: false
            })
        }

        return null;
    }
}
Savan2396
  • 112
  • 6
0

Template driven forms are quite easy to use. But as your application size increases it becomes complex to handle all the validations. As the name suggests- Template driven all the code for form and its validation is done mainly on the html template only so your template code increases. While in case of React Forms/Model driven you need to configure your control fields in the typescript only. So both are good and have there own advantages,so depending upon the requirement one should choose one from the other approach.