Reputation: 8681
I am trying to implement required field validation using directive and its not working. I need to apply the class to highlight the box red based on validation run. At the moment it looks like the requirefieldvalidator is not getting triggered. Not sure what is wrong here. Is it fine using it in the ngClass like the way I have done.
This is what I have tried
<label>Phone number</label>
<input type="text" placeholder="Phone number" formControlName="phoneNo" [ngClass]="{'isError' : 'requiredFieldValidator [submitted] = submitted'}" />
</div>
Directive
@Directive({
selector: '[requiredFieldValidator]',
providers: [{ provide: NG_VALIDATORS, useExisting: RequiredFieldValidatorDirective , multi: true}]
})
export class RequiredFieldValidatorDirective implements Validator {
@Input() submitted: boolean = false;
validate(control: AbstractControl): { [key: string]: any } {
return (this.submitted || control.touched) && control.errors?.required;
}
}
Upvotes: 1
Views: 963
Reputation: 73357
You cannot add directives like that inside ngClass, [ngClass]
expects possible variables, not directives. If you want to add a directive that does styles, I would use hostbinding instead and inject the formcontrol in the directive to check it's validity and apply class when needed.
So template would be:
<input
formControlName="phoneNo"
validityStyle
[submitted]="submitted"
/>
validityStyle
being our directive here.
As mentioned, we inject the formontrol into the directive, also take your submitted
variable and use HostBinding
to add your isError
class to the input field when wanted:
@Directive({
selector: '[validityStyle]',
})
export class ValidityStyleDirective {
@Input() submitted: boolean;
constructor(@Self() private ngControl: NgControl) {}
@HostBinding('class.isError')
get myClass() {
return (this.submitted || this.ngControl.touched) && !this.ngControl.valid
}
}
Here's a DEMO for your reference
Upvotes: 1