我使用反应式表单验证,每个输入字段都有一对条件。 我不想立刻显示所有错误,我正在寻找一种很好的方法来实现它。目前我的代码如下所示:
<div class="err-msg"
*ngIf="stbForm.get('firstName').invalid && (stbForm.get('firstName').dirty || stbForm.get('firstName').touched)">
<ng-container *ngIf="stbForm.get('firstName').hasError('minlength')">
Name musg have at least {{stbForm.get('firstName').getError('minlength').requiredLength}} characters
</ng-container>
<ng-container *ngIf="stbForm.get('firstName').hasError('maxlength')">
Name must have at most {{stbForm.get('firstName').getError('maxlength').requiredLength}} characters
</ng-container>
<ng-container *ngIf="stbForm.get('firstName').hasError('required') ||
stbForm.get('firstName').hasError('pattern')">
This field is required
</ng-container>
</div>
如果我想实现这一点,我需要为这些ifs添加更多条件并使其变得混乱。是否有更好更简单的方法?
我可以制作自定义指令甚至整个组件,但也许还有其他方式。
我可以为每个字段创建一个变量并从TS设置其值,但这需要扩展内置验证器
答案 0 :(得分:0)
如果只是这种情况,你可以尝试检查'firstname'字段是否为空:
''== modelForm.value ['image']
<div class = "err-msg"
* ngIf = "stbForm.get ('firstName'). invalid && (stbForm.get ('firstName'). dirty || stbForm.get ('firstName'). touched)">
<ng-container * ngIf = "''! = stbForm.value ['firstName'] && stbForm.get ('firstName'). hasError ('minlength')">
Name musg at least {{stbForm.get ('firstName'). GetError ('minlength'). RequiredLength}} characters
</ Ng Container>
<ng-container * ngIf = "''! = stbForm.value ['firstName'] && stbForm.get ('firstName'). hasError ('maxlength')">
Name must have at most {{stbForm.get ('firstName'). GetError ('maxlength'). RequiredLength}} characters
</ Ng Container>
<ng-container * ngIf = "'' == stbForm.value ['firstName'] && stbForm.get ('firstName'). hasError ('required') ||
stbForm.get ( 'firstName'). hasError ( 'pattern') ">
This field is required
</ Ng Container>
</ Div>
否则你应该使用一个变量,但总是使用带有* ngIf的控件...如果你觉得它太长了,代码和解决方案,等待别人,也许你将能够更好地建议! ; - )