angular - 使用 [attr.required] 动态添加所需属性后更新 FormControl
问题描述
我有一个定义为FormControl并绑定到ngModel的输入。它看起来如下:
HTML:
<!-- If this input is empty the POB input should be required -->
<input type="text"
id="addrs_house"
name="addrs_house"
#addrs_house="ngModel"
required
[ngStyle]="{hasError:addrs_house.invalid)}"
[(ngModel)]="model.house">
<!-- This input is dynamicaly required, dependant on the house input -->
<input type="text"
id="addrs_po"
name="addrs_po"
[(ngModel)]="model.pob"
#addrs_po="ngModel"
[attr.required]="model.house ? null : ''"
[ngStyle]="{hasError:addrs_po.invalid}">
TS:
// In the component Im refencing the FormInput model as so
@ViewChild('addrs_po') addrs_po: ElementRef;
问题:
required属性确实被添加到POB 输入中,但FormControl 的 ngModel 没有得到相应的错误对象更新。
解决方案
您应该使用属性绑定而不是属性绑定:
[required]="!model.house"
这将正确更新所需的状态
推荐阅读
- drawing - Use clipboard images to draw paths that repeat over entire length of the line
- azure-data-factory - 将文件从一个区域复制到其他区域 - Azure Data Lake Gen2
- reactjs - React-native:无法获取本地颁发者证书
- batch-file - =< 在 SET /P 和变量名之后的批处理文件中是什么意思?
- flutter - Flutter:动态更改选项卡文本
- java - 大摇大摆的日期时间正在转换为毫秒响应
- flutter - 在更改时存储列表变量
- selenium - 未创建会话:此版本的 ChromeDriver 仅支持 Chrome 版本 81
- wordpress - 使用 Laragon 为本地环境复制 wordpress 数据库
- c++ - 返回值优化和`std::move`之间的区别?