【发布时间】:2021-08-19 16:26:26
【问题描述】:
我正在尝试围绕 PrimeNG 日历控件创建一个包装器对象,并且在多年未使用 Angular 进行开发之后,我仍然需要注意,扩展控件及其所有控件功能没有简单的方法。
我想要的是,将必要的功能(例如设置验证状态,例如“ng-pristine”或“ng-dirty”)传递给内部控件。但这不能正常工作。也许有人已经解决了这个问题!
const noop = () => {
};
export const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CalendarFieldComponent),
multi: true
};
@Component({
selector: 'calendar-field',
templateUrl: './calendar-field.component.html',
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR],
})
export class CalendarFieldComponent implements ControlValueAccessor, Validator {
@Input() required = false;
@ViewChild(NgModel) model?: NgModel;
private innerValue: any = '';
private onTouchedCallback: () => void = noop;
private onChangeCallback: (_: any) => void = noop;
private onValidatorChange: (_: any) => void = noop;
get value(): any {
return this.innerValue;
};
set value(v: any) {
console.log(this.model);
this.model?.control.markAsDirty();
if (v !== this.innerValue) {
this.innerValue = v;
this.onChangeCallback(v);
}
}
onBlur() {
this.onTouchedCallback();
}
writeValue(value: any) {
if (value !== this.innerValue) {
this.innerValue = value;
}
}
registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
validate(control: AbstractControl): ValidationErrors | null {
return {'required': true};
}
registerOnValidatorChange(fn: () => void): void {
this.onValidatorChange = fn;
}
}
模板如下所示:
<p-calendar [(ngModel)]="value" styleClass="inputfield w-full" appendTo="body" [required]="required" (blur)="onBlur()"></p-calendar>
当我有一个包含上述控件的 FormGroup 时。提交表单后,我想验证所有字段,该字段已经使用以下代码工作。所有空字段都有一个红色边框(因为 ng-invalid),除了被包装的控件。
// code which validates all the fields when clicking on submit button
private validateForm(): boolean {
for (const controlKey of Object.keys(this.form.controls)) {
const control = this.form.controls[controlKey];
control.markAllAsTouched();
control.markAsDirty();
control.markAsTouched();
}
return !!this.form.valid;
}
包装控件获取类“ng-invalid ng-touched ng-dirty”,而内部控件只获取类“ng-untouched ng-pristine ng-invalid ng-star-inserted”。
我怎样才能同步这个(从包装器到内部)?
【问题讨论】:
标签: angular typescript validation primeng