首页 > 解决方案 > 使用 [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 没有得到相应的错误对象更新。

标签: angularangular5angular6angular4-forms

解决方案


您应该使用属性绑定而不是属性绑定:

[required]="!model.house"

这将正确更新所需的状态


推荐阅读