I am using a template-driven form with a custom validator on one of the fields :
<button type="button" (click)="myForm.submit()" [disabled]="!myForm.valid" class="btn">Save</button>
<form #myForm="ngForm" (ngSubmit)="submit()">
...
<input type="text"
class="validate"
[(ngModel)]="myDate"
name="myDate"
ngControl="myDate"
myValidator/>
</form>
myValidator :
import { Directive, forwardRef } from '@angular/core'
import { NG_VALIDATORS, FormControl, Validator } from '@angular/forms'
function check(s: string) {
...
}
function customValidation() {
return (c: FormControl) => {
return check(c.value) ? null : {
myValidator: false
}
}
}
@Directive({
selector: '[myValidator ][ngModel],[myValidator ][formControl]',
providers: [
{ provide: NG_VALIDATORS, useExisting: forwardRef(() => MyValidator), multi: true }
]
})
export class MyValidator implements Validator {
validator: Function
constructor() {
this.validator = customValidation()
}
validate(c: FormControl) {
return this.validator(c)
}
}
Everything is working just fine on the field. The only issues comes when the validator set the field to invalid, the form isn't set to invalid and thus the save button isn't disabled. I can't exactly get why. I guess I forgot a link between the validator and the form.
I am using angular_forms 0.3.0
Here is a plunkr : http://plnkr.co/edit/qUKYGFNLyjh6mNiqYY5I?p=preview which really seems to work... (rc.4 though)