Код: Выделить всё
import { Component, forwardRef, Input, OnInit } from '@angular/core';
import {
AbstractControl,
ControlValueAccessor,
FormsModule,
NG_VALIDATORS,
NG_VALUE_ACCESSOR,
ValidationErrors,
Validator,
} from '@angular/forms';
@Component({
selector: 'app-input',
standalone: true,
imports: [FormsModule],
templateUrl: './input.component.html',
styleUrl: './input.component.scss',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputComponent),
multi: true,
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => InputComponent),
multi: true,
},
],
})
export class InputComponent implements ControlValueAccessor, Validator {
@Input() value: string = '';
@Input() type: string = 'text';
@Input() placeholder: string = '';
@Input() disabled: boolean = false;
@Input() label: string = '';
// default to a random id unless one is provided.
@Input() id: string = '';
isInvalid: boolean = false;
touched: boolean = false;
onChange = (value: string) => {};
onTouched = () => {};
onValidationChange = () => {};
errorMessage: string = '';
writeValue(value: string): void {
this.value = value;
}
registerOnChange(onChange: any): void {
this.onChange = onChange;
}
registerOnTouched(onTouched: any): void {
this.onTouched = onTouched;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
onInputChange($event: Event) {
const input = $event.target as HTMLInputElement;
this.value = input.value;
this.onChange(this.value);
this.markAsTouched();
this.onValidationChange();
}
markAsTouched() {
if (!this.touched) {
this.onTouched();
this.touched = true;
}
}
validate(control: AbstractControl): ValidationErrors | null {
this.errorMessage = this.getErrorMessage(control.errors);
return control.errors;
}
registerOnValidatorChange(onValidationChange: () => void): void {
this.onValidationChange = onValidationChange;
}
private getErrorMessage(errors: ValidationErrors | null): string {
if (!this.touched || !errors) {
return '';
}
if (errors['required']) {
return 'This field is required';
}
if (errors['minLength']) {
return `Minimum length is ${errors['minLength'].requiredLength}.`;
}
return '';
}
}
У меня есть образец угловой проект, показывающий эту проблему здесь:
https://stackblitz.com/edit/stackblitz- ... nent.tsЧто я пробовал:
- Я изменил двустороннюю привязку [(ngModel)] и прослушиватель (ngModelChanges) на простое [значение] и (входной) прослушиватель, но это не помогло.
- Я зарегистрировал метод onValidationChange, но он не сработал.
Подробнее здесь: https://stackoverflow.com/questions/793 ... l-value-ac