【发布时间】:2021-08-13 12:28:54
【问题描述】:
我正在尝试使用自定义验证器将整个 fromGroup 设置为无效,这似乎不起作用...
下面代码的目标是比较 fromGroup 的两个实例。
- 如果匹配,则表示未进行任何更改,因此必须 无效。
- 否则不匹配表示已进行更改,因此必须 有效。
我的变量isValid 在我登录时可以正常工作。它根据变化变为真或假。
但我无法使 from 无效,我尝试了多种方式形成文章和堆栈溢出,其中有一个 stackblitz 似乎也不起作用。
喜欢this.updateCyclistForm.setErrors({ 'invalid': true}); 来自Angular 6 Required only one field from many fields Reactive Form
我看到很多类似的帖子都有 this one 使用控件,这里不是这种情况。
public updateCyclistForm: FormGroup
public savedStateOfForm: FormGroup
...
constructor(...) {
...
this.savedStateOfForm = new FormGroup({
status: new FormControl(this.currentReg.status, []),
role: new FormControl(this.currentReg.role, []),
passes: new FormControl({ data: this.passesUID }, [])
})
this.updateCyclistForm = new FormGroup({
status: new FormControl(this.currentReg.status, []),
role: new FormControl(this.currentReg.role, []),
passes: new FormControl({ data: this.passesUID }, [])
})
this.updateCyclistForm.setValidators(this.isValid(this.savedStateOfForm));
}
...
isValid = (clone: FormGroup): ValidatorFn => {
return (group: FormGroup): ValidationErrors => {
let isValid = JSON.stringify(clone.value) != JSON.stringify(control.value)
group.setErrors({ 'valid': isValid });
this.updateCyclistForm.setErrors({ 'valid': isValid });
return
}
}
HTML
<button type="submit" [disabled]="!updateCyclistForm.valid">Save</button>
按钮永远不会被禁用,为什么?我做错了什么?
编辑:
我也尝试使用类似于@Adam 的答案。这使我的button 终身禁用。
isValid = (clone: FormGroup): ValidatorFn => {
return (group: FormGroup) : ValidationErrors => {
return {
invalid: JSON.stringify(clone.value) != JSON.stringify(group.value) ? true : null
}
}
}
【问题讨论】:
-
好的,所以你的按钮被禁用了,你非常接近。如果您的控件有效,您必须从您的验证器返回 null。您不能返回任何其他内容,所有内容都在文档中。
-
我以为我正在返回
null,但它是一个空对象。感谢您的帮助
标签: javascript angularjs