我错了,Angular 6+ 的行为相同,但显示验证错误。忘了提一下,我正在使用“OnPush”策略。
在 Angular 6+ 上:
- 在组件初始化时触发“formControl”的“statusChanges”事件,状态为“Valid”,没有链接“asyncValidator”
- 在我的指令(“asyncValidator”)中调用此“验证”函数之后,收集错误
- 当使用空输入初始化组件视图时,输入具有“无效”下划线和预期错误
在 Angular 7+ 上:
1-2。相同的行为
- 输入出现时没有“无效”下划线和错误,直到没有聚焦,当它被触摸(聚焦)时 - 出现错误:\
这是我的“asyncValidate”指令:
@Input()
public propertyName: string;
private get _businessObject(): BusinessBase {
return this._fieldComponentBase.businessObject;
}
private _propertyChangedSubscription: Subscription;
constructor(private _fieldComponentBase: FieldComponentBase) {}
public ngOnDestroy() {
this.unsubscribeFromPropertyChangedEvent();
}
public validate(abstractControl: FormControl): Promise<ValidationErrors> | Observable<ValidationErrors> {
if (!this.propertyName) {
throw new Error('Property name of business object was not provided.');
}
if (!this._businessObject) {
throw new Error('Business object was not provided.');
}
return new Promise(resolve => {
const errors: ValidationErrors = {};
if (this._businessObject.shouldPristineFormControl(this.propertyName)) {
abstractControl.markAsPristine();
this._businessObject.removePropertyFormControlPristineStatus(this.propertyName);
}
if (abstractControl.dirty) {
this.unsubscribeFromPropertyChangedEvent();
this._propertyChangedSubscription = this._businessObject.propertyChanged
.subscribe((propertyChangedEvent: PropertyChangedEvent) => {
if (propertyChangedEvent.propertyName !== this.propertyName) {
return;
}
this.unsubscribeFromPropertyChangedEvent();
this.setErrors(errors);
resolve(errors);
});
} else {
this.setErrors(errors);
resolve(errors);
}
});
}
private setErrors(errors: ValidationErrors) {
this._businessObject.getBrokenRules(undefined, this.propertyName).forEach((brokenRule, index) => {
errors[index] = brokenRule.message;
});
}
private unsubscribeFromPropertyChangedEvent() {
if (!this._propertyChangedSubscription) {
return;
}
this._propertyChangedSubscription.unsubscribe();
this._propertyChangedSubscription = undefined;
}
这是我的表单控件的“statusChanges”监听器:
this.formControl.statusChanges.subscribe((status: 'VALID' | 'INVALID' | 'PENDING') => {
if (!this._formControlStatus) {
this._formControlStatus = status;
return;
}
if (status === 'PENDING' || status === 'VALID' && status === this._formControlStatus) {
return;
}
this._formControlStatus = status;
/**
* Should update component bindings if error calculation took too long.
*/
this.changeDetectorRef.markForCheck();
});