关于角度反应形式的代码清洁度的一个小问题... 在我们的表单中,我们经常会得到如下片段:
<div class="alert alert-danger"
*ngIf="formGroup.controls.openDateGroup.controls.preOpenDate.errors?.noFutureDateViolation; let errorInfo">
Pre open ({{errorInfo.value | febDate}}) date is not in the future
</div>
<div class="alert alert-danger"
*ngIf="formGroup.controls.openDateGroup.errors?.preOpenBeforeOpenViolation; let errorInfo">
Pre-open date ({{errorInfo.openDate | febDate}}) may not be after open date ({{errorInfo.preOpenDate | febDate}})
</div>
有没有办法使此片段更清洁?反应性表单指令(formGroupName和formControlName)知道它们在树结构中处于哪个级别,因此我认为应该可以以更简洁的方式进行这些检查...
答案 0 :(得分:0)
我喜欢使用这种模式:
1)将getter函数添加到要检查的字段的组件类中:
get openDateGroup() { return this.myFormGroup.get('openDateGroup'); }
2)在这样的模板中使用:
<div class="alert alert-danger" *ngIf="openDateGroup.errors?.preOpenBeforeOpenViolation; let errorInfo">
Pre-open date ({{errorInfo.openDate | febDate}}) may not be after open date ({{errorInfo.preOpenDate | febDate}})
</div>