Reputation: 121
I want to change the bordercolor of the next HTML-Element when my input is "dirty" and "valid".
HTML:
<input type="text" class="form-control" id="exampleId" formControlName="exampleId"
[ngClass]="{ 'is-valid': Form.get('exampleId')?.valid && vvtForm.get('exampleId')?.dirty) }"
(onKeyUp)="changeBorderColorOnValidation('exampleId')">
JavaScript:
changeBorderColorOnValidation(id) {
if (this.Form.get(id).valid) {
(document.querySelector('#' + id).nextSibling as HTMLElement).style.borderColor = '#28a745';
}
}
So far, this works, when you type something in the textarea the (onKeyUp)
validates if the textarea is empty or not and changes the bordercolor.
I want to have something cleaner like [ngRun]="functionToRun() | functionThatMustBeTrue".
Here:
[ngRun]="changeBorderColorOnValidation('exampleId') | Form.get('exampleId')?.valid && vvtForm.get('exampleId')?.dirty)
Does something like this exist?
Upvotes: 1
Views: 398
Reputation: 23
If I understand your question well, then what you want to do is already handled by angular. You just need to ad the .ng-dirty
class to your css. See example below and check the link to angular doc below for details.
[https://angular.io/guide/form-validation#control-status-css-classes][1]
Html:
<input type="text" class="form-control" id="exampleId" formControlName="exampleId"(onKeyUp)="changeBorderColorOnValidation('exampleId')">
Css:
.form-control .ng-invalid .ng-dirty {
border-color: red;
}
Upvotes: 0
Reputation: 2632
Use the Adjacent sibling combinator and Angular's status classes:
.ng-invalid.ng-dirty + * {
border-color: #28a745
}
Upvotes: 1