[英]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.我想分别验证每一个,并在输入包含无效值时添加一个类(例如,
is-invalid
)。 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.我知道 Angular 将
ng-invalid
添加到输入类列表中,但由于 Bootstrap 需要另一个类来显示错误,我想添加 Bootstrap 的类。
Is there any way to refer to the current element in Angular?有没有办法在 Angular 中引用当前元素? I'm using Angular 5. My template:
我正在使用 Angular 5。我的模板:
<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.引用当前元素(代码片段中的
thisElement
)的东西是我正在寻找的。 Does it exist?它存在吗?
To refer to the same element, you can use the sintax #thisElement
, where "thisElement" may be any name of your choice.要引用相同的元素,您可以使用
#thisElement
,其中“thisElement”可以是您选择的任何名称。 As you need to access some properties from the model it represents ( thisElement.invalid
), then you have to export it as ngModel
.由于您需要从它所代表的模型(
thisElement.invalid
)访问某些属性,因此您必须将其导出为ngModel
。
So the template would be something like this:所以模板将是这样的:
<input #thisElement="ngModel" [(ngModel)]="test" name="test" required [class.is-invalid]="thisElement.invalid && thisElement.touched">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.