gpt4 book ai didi

Angular 5 - 使用模板驱动表单的动态表单验证

转载 作者:行者123 更新时间:2023-12-05 00:40:01 26 4
gpt4 key购买 nike

我正在使用 ngFor 动态创建表单字段,每个字段都有唯一的 name 属性。我在他们的验证中挣扎。我的示例代码:

<div *ngFor="let dimension of lstShippingDimensions; let i = index" class="dimension-item">
<input type="text" name="units-{{i}}" [(ngModel)]="dimension.units"
class="first-f" placeholder="# of units" required>
<input type="text" name="width-{{i}}" [(ngModel)]="dimension.width"
class="second-f" placeholder="W" required>
<input type="text" name="height-{{i}}" [(ngModel)]="dimension.height"
class="third-f" placeholder="H" required>
<input type="text" name="length-{{i}}" [(ngModel)]="dimension.length"
class="forth-f" placeholder="L" required>
<select class="five-f" name="unitType-{{i}}" [(ngModel)]="dimension.unitType"
required>
<option>inches</option>
<option>feet</option>
</select>
<div *ngIf="!units-{{i}}.valid && units-{{i}}.touched" class="text-danger text-left">
<small *ngIf="units-{{i}}.errors.required">Field is required.</small>
</div>
</div>

最佳答案

通过添加 #units="ngModel" 以某种方式解决了这个问题。我猜 Angular 正在处理 ngFor 本身的引用。这工作得很好:

<div *ngFor="let dimension of lstShippingDimensions; let i = index" class="dimension-item">
<input type="text" name="units-{{i}}" #units="ngModel" [(ngModel)]="dimension.units" class="first-f" placeholder="# of units" required>
<input type="text" name="width-{{i}}" [(ngModel)]="dimension.width" class="second-f" placeholder="W" required>
<input type="text" name="height-{{i}}" [(ngModel)]="dimension.height" class="third-f" placeholder="H" required>
<input type="text" name="length-{{i}}" [(ngModel)]="dimension.length" class="forth-f" placeholder="L" required>
<select class="five-f" name="unitType-{{i}}" [(ngModel)]="dimension.unitType" required>
<option>inches</option>
<option>feet</option>
</select>
<div *ngIf="!units.valid && units.touched" class="text-danger text-left">
<small># of units is required.</small>
</div>
</div>

关于Angular 5 - 使用模板驱动表单的动态表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51441316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com