gpt4 book ai didi

angular - 为什么在 for 循环中未定义使用 ngModel 的模板引用变量?

转载 作者:太空狗 更新时间:2023-10-29 18:35:18 25 4
gpt4 key购买 nike

我正在尝试在 HTML 模板中获取 DOM 元素以禁用/启用基于输入值并使用 ngModel 的表单按钮: #Custom_FirstName="ngModel" 。输入是分隔组件中的自定义字段。

我的问题是元素 Custom_FirstName总是 undefined我发现它与 For Loop ngFor 有关.当我删除 ngFor , 错误已修复。但这并不能解决我的问题,因为我需要 for 循环,因为用户可以使用 firstName 添加多个输入文本和用户。动态地。

代码:

<div *ngFor="let el of users.departments.admins; let i=index; trackBy: trackByFn"
<input-text [name]="'firstanme'"
[(ngModel)]="el.firstName"
[ngModelOptions]="{standalone: true}"
[readonly]="false"
[required]="true"
labelText="First Name"
#Custom_FirstName="ngModel">
</input-text>
</div>

按钮:

<button [disabled]="!Custom_FirstName.value || ....>

我一直在检查 official Doc ,但我找不到解决办法。任何提示如何解决这个问题?

最佳答案

官方文档says :

The scope of a reference variable is the entire template. So, don't define the same variable name more than once in the same template as the runtime value will be unpredictable.

因为您已经绑定(bind)了数据输入,只需跟踪数据即可。添加到您的组件:

hasEmptyValue() {
return users.departments.admins
.some(admin => !admin.firstName || admin.firstName.length===0);
}

并在模板中进行更改:

<button [disabled]="hasEmptyValue() || ....>

关于angular - 为什么在 for 循环中未定义使用 ngModel 的模板引用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57248622/

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