0

I want to create a custom form control that handles any errors on itself. This means showing the error inside this component. I created a component which implements ControlValueAccessor. I can read the error form the form like this: form.controls.myfieldname.errors.aErrorName so I pass form.controls.myfieldname to my constom control.

Is there a better way to create field validation for a custom form control?

My custom control:

@Component({
    selector: 'input-text2',
    templateUrl: './input-text2.component.html',
    styleUrls: ['/input-base2.scss', './input-text2.component.scss'],
    providers: [
        { provide: NG_VALUE_ACCESSOR, multi: true, useExisting: InputText2Component }
    ]
})
export class InputText2Component implements ControlValueAccessor {
    // The control field: form.controls.fieldname
    @Input() field;

    @Input() label: string;
    @Input() errorMessage: string;

    value: string;
    valueChange: (value: any) => void;
    _onTouched: (value: any) => void;


    writeValue(value: any): void {
        this.value = value;
        this.createClasses(this.size);
    }

    registerOnChange(fn: (value: any) => void): void {
        this.valueChange = fn;
    }

    registerOnTouched(fn: (value: any) => void): void {
        this._onTouched = fn;
    }

}

Layout:

<div  *ngIf="field?.errors && field?.touched">
    invalid
</div>

Form:

<form novalidate #form="ngForm">
    <input-text2 [field]="form.controls.fieldname" name="fieldname" errorMessage="My error message" label="My label"  [(ngModel)]="model"
        custom-validator>
    </input-text2>
</form>

1 Answer 1

0

So I found an answer

I added this to my control:

private ngControl: NgControl;

constructor(private injector: Injector) {

}

ngOnInit(): void {
    this.ngControl = this.injector.get(NgControl);
}

ngControl is now basically the same as my field property. Next I could remove field completely and replace is with ngControl.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.