Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: Refer to current element in a template

Tags:

angular

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?

like image 566
Iván Pérez Avatar asked Feb 19 '18 12:02

Iván Pérez


1 Answers

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">
like image 131
Iván Pérez Avatar answered Oct 01 '22 20:10

Iván Pérez