If you desire validation to change the color to red, follow these steps. Otherwise, simply copy the CSS style provided below:
Here is the outcome:
<div class="row mb-3">
<div class="col-md-12">
<label for="companyId" class="form-label">Company</label>
<ng-select placeholder="select a company" appNgSelectWorkaroundValidator
formControlName="companyId" [items]="companies" bindValue="id" bindLabel="name"
required>
</ng-select>
</div>
</div>
A new appNgSelectWorkaroundValidator
directive was added to the ng select, automatically applying the isvalid CSS state.
This meets our requirements.
Let's create a directive as the first step.
import { Directive, HostBinding, Optional, Self } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[appNgSelectWorkaroundValidator]',
standalone: true,
})
export class NgSelectWorkaroundValidator {
constructor(@Optional() @Self() public ngControl: NgControl) {}
@HostBinding('class.is-invalid') get isInvalid(): boolean {
// The control is invalid and has been touched.
return this.ngControl
? this.ngControl.invalid &&
(this.ngControl.dirty || this.ngControl.touched)
: false;
}
}
Don't forget to set the CSS globally somewhere:
.is-invalid {
border: 1px solid red;
border-radius: 4px; /* Optional, for rounded corners */
}
And make sure to import the directive in your component:
@Component({
selector: 'app-some-component',
standalone: true,
imports: [ NgSelectWorkaroundValidator],