angular - Angular Reactive Forms 使用插值在输入上动态生成验证属性
问题描述
在我看来,使用插值在输入上动态生成验证属性中引发了完全相同的问题,但是我正在寻找解决方案Angular
,而不是AngularJS
.
在我的反应式表单中,我使用了这样的验证器:
public contactForm: FormGroup = this.formBuilder.group({
...
formControlDescription: [
'',
Validators.compose([
Validators.maxLength(5000),
Validators.minLength(30),
Validators.required,
]),
],
...
});
在html
我以5000
这种方式对数字进行硬编码:
<mat-hint align="end">{{ contactForm.get('formControlDescription')!.value.length }} / 5000</mat-hint>
问题:有没有办法动态访问contactForm
's中的formControlDescription
's ?Validators.maxLength(5000)
html
解决方案
您可以从最小/最大验证器中获取错误对象,如下所示:
<mat-hint align="end">{{ contactForm.get('formControlDescription')?.errors.maxlength?.actualLength }} / {{ contactForm.get('formControlDescription')?.errors.maxlength?.requiredLength }} </mat-hint>
更清洁的版本:
<mat-hint align="end">
{{ contactForm.errors?.formControlDescription?.maxlength?.actualLength}} /
{{ contactForm.errors?.formControlDescription?.maxlength?.requiredLength}}
</mat-hint>
更新
只有当验证器被触发并呈现为无效时,角度验证器的值才会对您可用。
例如,如果你有minLength(10)
,它会在你被触摸的那一刻给你无效的输入,直到字符达到或超过 10 个。对于maxLength(20)
,它只会在errors
触发后在对象中可用,即用户输入的字符超过 20 个。
如果您打算使用actualLength
和requiredLength
一致地向用户显示统计信息,则会出现问题,因为它们只会在其中一个minLength
或maxLength
无效时出现。
如前所述,对您来说最好的方法是使用单独的变量来设置和显示所需的长度。例如:
const validatorOptions = {
maxLength: 5000,
minLength: 5
}
然后在您的模板中使用它:
<mat-hint align="end">{{ contactForm.controls.formControlDescription?.value.length }} / {{validatorOptions.maxLength}}</mat-hint>
推荐阅读
- lua - 如何在 Lua 中测试 None 值?
- javascript - 将内联样式更改为样式组件
- perl - 未知 PerlIO 层类 ':utf8 :std'
- html - 如何在 Flask 中获取会话变量,并将其显示在 HTML 导航栏中并将其作为下拉按钮?
- swift - 如何初始化绑定:SwiftUI 中的 Bool 变量?
- php - 当我向 localhost 提交信息时,出现 PHP 代码
- laravel - Laravel:网站内未定义的变量帖子
- javascript - 重新渲染后视频 onEnd 触发两次
- php - 使用 mysqli_num_rows() 时没有回显
- react-native - 在 React Native 中上传视频时出错