Reputation: 2445
In my Angular app, I need to add/remove CSS classes based on whether or not a FormControl has been touched, is dirty, is invalid, etc.
I'm using the ngClass directive to do this:
<div class="form-group has-required"
[ngClass]="{'has-error':
(conditionsForm.get('acceptTerms').touched || conditionsForm.get('acceptTerms').dirty)
&& conditionsForm.get('acceptTerms').errors}">
</div
Here is what I have in my Typescript currently:
ngOnInit() {
this.conditionsForm = this.fb.group({
acceptTerms: new FormControl('', Validators.required),
insuredType: new FormControl('', Validators.required),
reportInjury: new FormControl('', Validators.required)
});
}
As the above conditional is quite long, I would like to move it into my Typescript file.
Is there a particular method to doing this? I'm not sure how I can do it. Can someone please tell me what my approach should be?
Thanks a lot in advance!
Upvotes: 2
Views: 386
Reputation: 10697
I would go with this which will work for all formControls:
public hasError(formControlName: string): boolean {
if (this.user.get(formControlName).errors) {
return true;
}
else {
return false;
}
}
HTML Code:
<div [ngClass]="{'has-error': hasError('acceptTerms')}">
// Other HTML
</div>
So in case of other form controls you can easily use it as:
<div [ngClass]="{'has-error': hasError('another_formcontrol')}">
//
</div>
Upvotes: 1
Reputation: 180
I dont think you needs to check both dirty and touched. Checkout the reactive form documentation - https://angular.io/guide/reactive-forms
<div class="form-group has-required"
[ngClass]="{'has-error': conditionsForm.acceptTerms.touched && conditionsForm.acceptTerms.errors}">
</div>
Upvotes: 1
Reputation: 14679
You can try another route: Angular OOTB assigns classes such as ng-dirty
, ng-touched
, ng-invalid
to form controls, you can style those in the component's stylesheet.
input.ng-invalid.ng-dirty {
// style definition here
}
Upvotes: 1
Reputation: 6183
You can just wrap it into a function in your component:
public _hasErrorClass(): boolean {
return (this.conditionsForm.get('acceptTerms').touched || this.conditionsForm.get('acceptTerms').dirty)
&& this.conditionsForm.get('acceptTerms').errors;
}
And then use it in your template:
<div class="form-group has-required" [ngClass]="{'has-error': _hasErrorClass()}"></div>
Upvotes: 1