如何解决当Angular表单无效时,如何延迟错误消息,但是一旦有效就将其删除?
我的Angular 9 Reactive表单中有两个字段都必须填写或都为空。当用户填充其中一个字段而另一个字段为空时,我想延迟错误消息。最终,我会显示一个错误。有一个功能输出错误消息或空数组,以显示在html模板中。我正在使用RxJs debounceTime
运算符来延迟错误消息。
问题:用户填写完第二个字段后,消息将保留。表格生效后如何隐藏它们?
示例代码
const form = formBuilder.group({
//other controls with validation
treatmentCount: undefined,controlCount: undefined,},{
validators: this.validatorFunction() // either both controls must be filled or none
} )
function errors(treatment: number | undefined,control: number | undefined ): string[] {
...
return isValid?[]:['Oops! Error'] }
const errorMessages$: Observable<string[]> = form.valueChanges.pipe(
debounceTime(2000),map( value => {return errors(value.treatmentCount,value.controlCounnt)},)) // this is displayed in the html template
我尝试merge
errorMessages$
时出现“没有错误”,只能在表格有效后立即触发[ ]
。但是,这实际上消除了显示错误的延迟。尝试updateOn
模糊无法解决问题,并且用户体验更差。
PS。我已经在互联网上搜寻了一个答案,但可悲的是我的具体问题并不多。
解决方法
您需要在去抖动时间之前检查错误,然后再使用去抖动时间。
类似这样的东西:
const errorMessages$: Observable<string[]> = form.valueChanges.pipe(
map(value => errors(value.treatmentCount,value.controlCounnt)),debounce(error => error ? timer(2000) : EMPTY)
) // this is displayed in the html template
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。