首页 > 解决方案 > 来自对象数组的角度多个输入

问题描述

我需要显示对象数组中的多个输入字段(本例中为 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>

标签: angular

解决方案


将模板引用变量添加到您的输入并使用它指定元素。

这是我的样子:

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

(此示例不使用索引,但不应将索引作为模板引用变量的一部分。)


推荐阅读