angular - Angular 6,this.formGroup.updateValueAndValidity() 无法正常工作
问题描述
我正在尝试formGroup
根据特定条件在控件中添加和删除验证器。
当我通过formGroup.updateValueAndValidity()
整个表单更新验证器时,它没有更新,就好像我专门为每个控件申请一样formGroup.get('formControl').updateValueAndValidity()
,它正在工作,但我必须为每个控件编写,我希望这不是正确的方法。我究竟做错了什么?
if (data == 'x') {
this.myForm.get('control2').setValue(null);
this.myForm.get('control2').setValidators(Validators.nullValidator);
this.myForm.get('control1').setValidators(Validators.required);
} else if (data == 'y') {
this.myForm.get('control1').setValue(null);
this.myForm.get('control1').setValidators(Validators.nullValidator);
this.myForm.get('control2').setValidators(Validators.required);
}
this.myForm.get('control1').updateValueAndValidity();
this.myForm.get('control2').updateValueAndValidity();
这是有效的,但是,
this.myForm.updateValueAndValidity();
这是行不通的。
解决方案
updateValueAndValidity()
是自下而上的,因此如果您在控件上调用此方法,它将仅检查此控件及其父控件的验证,但不检查其子控件。
有关更多详细信息,请参阅github 上的AbstractControl#updateValueAndValidity以了解其工作原理。
updateValueAndValidity(opts: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
this._setInitialStatus();
this._updateValue();
if (this.enabled) {
this._cancelExistingSubscription();
(this as{errors: ValidationErrors | null}).errors = this._runValidator();
(this as{status: string}).status = this._calculateStatus();
if (this.status === VALID || this.status === PENDING) {
this._runAsyncValidator(opts.emitEvent);
}
}
if (opts.emitEvent !== false) {
(this.valueChanges as EventEmitter<any>).emit(this.value);
(this.statusChanges as EventEmitter<string>).emit(this.status);
}
if (this._parent && !opts.onlySelf) {
this._parent.updateValueAndValidity(opts);
}
}
推荐阅读
- javascript - 设置日期值
- angular - 跨域问题。需要调用获取请求到firebase托管的angular2应用程序
- reporting-services - SSRS在excel上导出日期时间不同的毫秒?
- bash - 将项目目录设置为 Dockerfile 中 Entrypoint 的 Workdir
- html - 导航栏在响应视图中推送下面的内容(Bootstrap 4)
- php - 在 PHP 上使用 GD 不起作用 - 只有黑色方块
- python - Django 数据库身份验证插件错误
- android - 过滤由视图模型的 LiveData 条目填充的回收器视图
- asp.net - 具有来自 Web 根目录的反应加载图像的 asp.net 核心
- javascript - Ace 编辑器 - 清除选择不起作用