【发布时间】:2017-12-08 09:12:55
【问题描述】:
在我们的 Angular 表单中(我们使用 template driven forms),我们有一个动态呈现的输入字段列表,因此,我们需要验证。在此之后:Using template driven form with dynamic input list (ngFor) 我没有再进一步,因为它似乎已经过时,因为 plunkr 示例不起作用。
那是我们的 tbody 呈现我们的列表:
<tbody>
<tr *ngFor="let item of items; let i=index">
<td><span>{{ item.categoryName }}</span></td>
<td class="text-right">
<input *ngIf="editMode"
type="number"
tabindex="1"
autocomplete="off"
[(ngModel)]="item.value" name="value-{{item.categoryId}}" #value="ngModel"
required
/>
{{value.valid}} <!--As I'm using ngForm I was expecting to receive false or true here-->
<span *ngIf="!editMode">{{ item.value }}</span>
</td>
<td>
<app-status [status]="item.status"></app-status>
</td>
</tr>
</tbody>
这个工作正常,可以看到列表,但是验证不起作用。
如果我尝试:{{value.valid}} 我收到以下错误:
ERROR TypeError: Cannot read property 'valid' of undefined
意味着,我的 ngModel 实例不起作用。
我错过了什么?
【问题讨论】:
-
这里的问题可能是模板引用变量。每个输入框都有 same 模板引用变量。根据文档:
The scope of a reference variable is the entire template. Do not define the same variable name more than once in the same template. The runtime value will be unpredictable.来自:angular.io/guide/… -
我没明白你的意思
-
对于每个输入框,您都定义了一个
value变量,但是该变量的范围并不与输入框隔离,它可以被模板的整个范围引用。因此,特别是在您循环并在模板中分别创建这些内容的情况下,可能会在此过程中出现问题,因此会发出警告: -
#value 是一个模板引用变量。您正在将具有此 same 名称的模板引用变量添加到 every 输入框。根据文档,您不应在模板中多次使用相同的模板引用变量。
-
如果我有迭代,解决方案是什么?创建一个范围函数来为我验证我的价值?那么就不需要
required属性了吗?
标签: angular validation