Iván Pérez
Iván Pérez

Reputation: 2529

Angular: Refer to current element in a template

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?

Upvotes: 10

Views: 2289

Answers (1)

Iv&#225;n P&#233;rez
Iv&#225;n P&#233;rez

Reputation: 2529

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">

Upvotes: 3

Related Questions