我在angular 4中具有以下HTML组件:
<div *ngFor="let item of items; let i = index" class="row">
<div class="col-md-7">
<select
class="form-control form-control-sm"
name="durationTime{{i}}"
required
[(ngModel)]="item.durationTime"
#durationTime{{i}}="ngModel"
[ngClass]="{'is-valid': durationTime{{i}}.valid && durationTime{{i}}.touched, 'is-invalid': durationTime{{i}}.invalid && durationTime{{i}}.touched}">
<option [ngValue]="null" disabled selected>Elige</option>
<option *ngFor="let item of durationTimes" [ngValue]="item"> {{item}} </option>
</select>
<small *ngIf="durationTime{{i}}.invalid && durationTime{{i}}.touched"
class="form-text text-muted-error">
!Debes seleccionar una opción!
</small>
</div>
</div>
我需要验证控件,但出现此错误:
Parser Error: Got interpolation ({{}}) where expression was expected at column 25 in [{'is-valid': durationTime{{i}}.valid && durationTime{{i}}.touched, 'is-invalid': durationTime{{i}}.invalid && durationTime{{i}}.touched}] in
我的问题是如何在angular 4的[ngClass]和ngIf内部使用局部模板变量?
答案 0 :(得分:2)
您不需要在ngFor
循环的每次迭代中为template reference variable赋予不同的名称。只要给它起一个普通的名字,如#durationTime
。 ngClass
绑定和ngIf
条件将使用特定于循环迭代的变量实例。
<div *ngFor="let item of items; let i = index" class="row">
<div class="col-md-7">
<select
class="form-control form-control-sm"
name="durationTime{{i}}"
required
[(ngModel)]="item.durationTime"
#durationTime="ngModel"
[ngClass]="{'is-valid': durationTime.valid && durationTime.touched, 'is-invalid': durationTime.invalid && durationTime.touched}">
<option [ngValue]="null" disabled selected>Elige</option>
<option *ngFor="let item of durationTimes" [ngValue]="item"> {{item}} </option>
</select>
<small *ngIf="durationTime.invalid && durationTime.touched"
class="form-text text-muted-error">
!Debes seleccionar una opción!
</small>
</div>
</div>