vbi*_*nko 6 validation typescript angular angular-reactive-forms controlvalueaccessor
这是诀窍:
问题:
ControlValueAccessor 接口中的方法 validate() 在值更改后立即调用,并且不等待异步验证器。当然,控制无效且待定(因为正在进行验证)并且主表单也无效且待定。一切正常。
但。当异步验证器完成验证并返回 null(意味着值有效)时,自定义控件将有效并且状态也变为有效,但父级仍然无效且处于挂起状态,因为值访问器的 validate() 没有再次调用。
我试图从 validate() 方法返回 observable,但主表单将其解释为错误对象。
我找到了解决方法:当异步验证器完成验证时,从自定义控件传播更改事件。它迫使主窗体再次调用 validate() 方法并获得正确的有效状态。但它看起来又脏又粗糙。
问题是: 需要做什么才能使父表单由子自定义控件的异步验证器管理?必须说它适用于同步验证器。
所有项目代码都可以在这里找到:https : //stackblitz.com/edit/angular-fdcrbl
主表单模板:
<form [formGroup]="mainForm">
<child-control formControlName="childControl"></child-control>
</form>
Run Code Online (Sandbox Code Playgroud)
主窗体类:
import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup } from "@angular/forms";
@Component({
selector: "my-app",
templateUrl: "./app.component.html"
})
export class AppComponent implements OnInit {
mainForm: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.mainForm = this.formBuilder.group({
childControl: this.formBuilder.control("")
});
}
}
Run Code Online (Sandbox Code Playgroud)
自定义子控件模板:
<div [formGroup]="childForm">
<div class="form-group">
<label translate>Child control: </label>
<input type="text" formControlName="childControl">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
自定义子控件类:
import { Component, OnInit } from "@angular/core";
import { AppValidator } from "../app.validator";
import {
FormGroup,
AsyncValidator,
FormBuilder,
NG_VALUE_ACCESSOR,
NG_ASYNC_VALIDATORS,
ValidationErrors,
ControlValueAccessor
} from "@angular/forms";
import { Observable } from "rxjs";
import { map, first } from "rxjs/operators";
@Component({
templateUrl: "./child-control.component.html",
selector: "child-control",
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: ChildControlComponent,
multi: true
},
{
provide: NG_ASYNC_VALIDATORS,
useExisting: ChildControlComponent,
multi: true
}
]
})
export class ChildControlComponent
implements ControlValueAccessor, AsyncValidator, OnInit {
childForm: FormGroup;
constructor(
private formBuilder: FormBuilder,
private appValidator: AppValidator
) {}
ngOnInit() {
this.childForm = this.formBuilder.group({
childControl: this.formBuilder.control(
"",
[],
[this.appValidator.asyncValidation()]
)
});
this.childForm.statusChanges.subscribe(status => {
console.log("subscribe", status);
});
}
// region CVA
public onTouched: () => void = () => {};
writeValue(val: any): void {
if (!val) {
return;
}
this.childForm.patchValue(val);
}
registerOnChange(fn: () => void): void {
this.childForm.valueChanges.subscribe(fn);
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
setDisabledState?(isDisabled: boolean): void {
isDisabled ? this.childForm.disable() : this.childForm.enable();
}
validate(): Observable<ValidationErrors | null> {
console.log('validate');
// return this.taxCountriesForm.valid ? null : { invalid: true };
return this.childForm.statusChanges.pipe(
map(status => {
console.log('pipe', status);
return status == "VALID" ? null : { invalid: true };
}),
);
}
// endregion
}
Run Code Online (Sandbox Code Playgroud)
问题是,在childForm.statusChanges发出时,异步验证器的订阅将已经被取消。
这是因为之前childForm.valueChanges发出。 childForm.statusChanges
当childForm.valueChanges发出时,注册的onChanged回调函数将被调用:
registerOnChange(fn: () => void): void {
this.childForm.valueChanges.subscribe(fn);
}
Run Code Online (Sandbox Code Playgroud)
这将导致 FormControl( controlChild) 更新其值
function setUpViewChangePipeline(control: FormControl, dir: NgControl): void {
dir.valueAccessor !.registerOnChange((newValue: any) => {
/* ... */
if (control.updateOn === 'change') updateControl(control, dir);
});
}
// Update the MODEL based on the VIEW's value
function updateControl(control: FormControl, dir: NgControl): void {
/* ... */
// Will in turn call `control.setValueAndValidity`
control.setValue(control._pendingValue, {emitModelToViewChange: false});
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
意味着updateValueAndValidity将达到:
updateValueAndValidity(opts: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
this._setInitialStatus();
this._updateValue();
if (this.enabled) {
this._cancelExistingSubscription(); // <- here the existing subscription is cancelled!
(this as{errors: ValidationErrors | null}).errors = this._runValidator(); // Sync validators
(this as{status: string}).status = this._calculateStatus(); // VALID | INVALID | PENDING | DISABLED
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我想出的方法允许您的自定义组件跳过实现ControlValueAccesor和AsyncValidator接口。
<form [formGroup]="mainForm">
<child-control></child-control>
</form>
Run Code Online (Sandbox Code Playgroud)
ngOnInit() {
this.mainForm = this.formBuilder.group({
childControl: this.formBuilder.control("", null, [this.appValidator.asyncValidation()])
});
}
Run Code Online (Sandbox Code Playgroud)
<div class="form-group">
<h4 translate>Child control with async validation: </h4>
<input type="text" formControlName="childControl">
</div>
Run Code Online (Sandbox Code Playgroud)
@Component({
templateUrl: "./child-control.component.html",
selector: "child-control",
providers: [
],
viewProviders: [
{ provide: ControlContainer, useExisting: FormGroupDirective }
]
})
export class ChildControlComponent
implements OnInit { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
这里的关键是提供{ provide: ControlContainer, useExisting: FormGroupDirective }里面的viewProviders。
这是因为在内部FormControlName,父抽象控件是在装饰器的帮助下检索的@Host。这允许您指定使用您想要获取的装饰器viewProviders声明的依赖项(在本例中为)。像这样检索它@HostControlContainer
FormControlName@Optional() @Host() @SkipSelf() parent: ControlContainer