Reputation: 41264
I have an input field with optional value (not required). When I interact with it, I get classes ng-dirty
, ng-valid
, ng-touched
<input type="text" formControlName="url"
[class.has-value]="quickSetupForm.controls.url.value !== ''"
placeholder="www.example.com"
id="url">
input.ng-valid.ng-dirty.has-value
border-bottom 2px solid green
What's the best way to do has-value check for all formControls? Or is there some other way to do this?
I don't want input.ng-valid.ng-dirty
selector to affect inputs that are not required, but user has entered and deleted something (making them dirty
, touched
, valid
).
Upvotes: 3
Views: 510
Reputation: 41264
I did it with this directive:
/* tslint:disable:directive-selector-prefix */
import { Directive, ElementRef, HostListener, Renderer } from '@angular/core';
@Directive({
selector: '[formControlName]'
})
export class FormControlValueDirective {
private control: HTMLInputElement;
constructor(
private renderer: Renderer,
private elementRef: ElementRef) {
this.control = this.elementRef.nativeElement;
}
@HostListener('input') onInput() {
if (this.control instanceof HTMLInputElement) {
this.renderer.setElementClass(this.control, 'has-value', this.control.value !== '');
}
}
}
Upvotes: 1