【发布时间】:2019-12-12 23:57:44
【问题描述】:
我在迁移到 Angular 7 的第一周,我一直在使用基于模板的基本验证在我的项目中做基本表单,但我现在需要基于一个字段的值必须是验证表单比别人高
我尝试在组件控制器中使用这些值本身,但是虽然我能够确认这些值是否有效,但我无法使用此代码向用户展示问题所在
if (issueThresholdForm.value.lowScore > issueThresholdForm.value.highScore) {
// Show user error
// This is the messing part, I guess
}
这是我正在使用的模板
<div *ngIf="_issueCategory">
<form (submit)="submitIssueThreshold(issueThresholdForm)" #issueThresholdForm="ngForm">
<mat-form-field class="half-width" floatLabel="always">
<mat-label [translate]="'issueThreshold.modals.highScore'"></mat-label>
<input name="highScore" type="number" matInput placeholder="0" [(ngModel)]="_issueCategory.highScore"
required #highScore="ngModel">
</mat-form-field>
<mat-form-field class="half-width" floatLabel="always">
<mat-label [translate]="'issueThreshold.modals.lowScore'"></mat-label>
<input name="lowScore" type="number" matInput placeholder="0" [(ngModel)]="_issueCategory.lowScore"
required #lowScore="ngModel">
</mat-form-field>
<mat-form-field class="full-width" floatLabel="always">
<mat-label [translate]="'issueThreshold.modals.description'"></mat-label>
<textarea name="description" matInput [(ngModel)]="_issueCategory.thresholdDescription">
</textarea>
</mat-form-field>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" [translate]="'modal-confirm.cancel'"></button>
<button type="submit" class="btn btn-primary primary" [disabled]="issueThresholdForm.invalid || issueThresholdForm.pristine" [translate]="'modal-confirm.submit'"></button>
</div>
</form>
</div>
【问题讨论】:
-
添加stackBlitz URL,很容易得到快速的答复
-
不相关,但我建议转向反应式表单,使用自定义验证器轻松处理此类情况。当然你也可以在模板驱动的表单中做一个自定义验证器。
-
响应式表单也有助于编写更好的单元测试
标签: angular typescript angular-validation