我需要显示对象数组(在此示例中为testtttt)的多个输入字段。如果输入字段未填写,我需要Action ({{i +1}})
才能获得红色。如何从输入中获取测试有效状态?
我知道可以询问输入(action.valid)
的名称的有效状态。但是在这种情况下,名称的名称中带有数字i。
<div *ngFor="let test of testtttt; let i = index" layout="column" layout-wrap>
<div>
<div>
<span>Action ({{i + 1}}):</span>
<div>
<mat-label>
<mat-form-field>
<input matInput [(ngModel)]="componentTest[i].description" required name="action + {{i}}">
</mat-form-field>
</mat-label>
</div>
</div>
</div>
</div
我尝试了这个,但是给出了错误。
<span [ngClass]="{'red': !(action + i).valid}">Action ({{i + 1}}):</span>
答案 0 :(得分:0)
在输入中添加模板引用变量,并使用它指定元素。
这是我的样子:
<div class="form-group"
[ngClass]="{'has-error': (firstNameVar.touched || firstNameVar.dirty) && !firstNameVar.valid }">
<label class="col-md-2 control-label"
for="firstNameId">First Name</label>
<div class="col-md-8">
<input class="form-control"
id="firstNameId"
type="text"
placeholder="First Name (required)"
required
minlength="3"
[(ngModel)]=customer.firstName
name="firstName"
#firstNameVar="ngModel" />
<span class="help-block" *ngIf="(firstNameVar.touched || firstNameVar.dirty) && firstNameVar.errors">
<span *ngIf="firstNameVar.errors.required">
Please enter your first name.
</span>
<span *ngIf="firstNameVar.errors.minlength">
The first name must be longer than 3 characters.
</span>
</span>
</div>
</div>
请注意模板引用变量:#firstNameVar
。
(此示例不使用索引,但不应将索引作为模板引用变量的一部分。)