我的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。我已经在互联网上搜寻了一个答案,但可悲的是我的具体问题并不多。
答案 0 :(得分:1)
您需要在去抖动时间之前检查错误,然后再使用去抖动时间。
类似这样的东西:
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