I have a form with several inputs. I want to validate each one separately, and add a class (for example, is-invalid
) when the input contains an invalid value. I know Angular adds ng-invalid
to the input class list, but as Bootstrap needs another class to show the error, I would like to add Bootstrap's class.
Is there any way to refer to the current element in Angular? I'm using Angular 5. My template:
<input [(ngModel)]="test" name="test" required [class.is-invalid]="thisElement.invalid && thisElement.touched">
^^^^^^^^^^^
Something to refer to the current element (thisElement
in the snippet) is what I'm looking for. Does it exist?
To refer to the same element, you can use the sintax #thisElement
, where "thisElement" may be any name of your choice. As you need to access some properties from the model it represents (thisElement.invalid
), then you have to export it as ngModel
.
So the template would be something like this:
<input #thisElement="ngModel" [(ngModel)]="test" name="test" required [class.is-invalid]="thisElement.invalid && thisElement.touched">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With