Given:
<div class="form-group" [fieldValidity]="email">
<label for="email" class="sr-only">Email</label>
<input [(ngModel)]="model.email" ngControl="email" required>
</div>
And my custom [fieldValidity] directive:
import { Directive, ElementRef, Input } from 'angular2/core';
import {NgControlName} from 'angular2/common';
@Directive({
selector: '[fieldValidity]'
})
export class FieldValidityDirective {
private el: HTMLElement;
@Input('fieldValidity') field: NgControlName;
constructor(el: ElementRef) {
this.el = el.nativeElement;
}
private _onValidityChange(value: string) {
//TODO test field.valid || field.pristine
if (?) {
this.el.classList.remove('has-error');
} else {
this.el.classList.add('has-error');
}
}
}
How can I get subscribe to the field.valid && field .pristine values to show the error? (I've marked it with 'TODO' below)
You should use the markAsDirty method, like this: control. markAsDirty(); This will also mark all direct ancestors as dirty to maintain the model.
An easy way is to use the data-driven approach with the [ngClass] directive as follows
Template:
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div class="form-group">
<div [ngClass]="{'has-error': form.controls['description'].invalid}">
<input type="text" formControlName="description" class="form-control" required [(ngModel)]="description">
</div>
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
Component:
export class FormComponent implements OnInit {
private form: FormGroup;
private description: string;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.form = this.formBuilder.group({
description: new FormControl('')
});
}
}
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