Implementing a custom form control and display error messages within its own template

Discussão em 'Angular' iniciado por balteo, Fevereiro 7, 2025.

  1. balteo

    balteo Guest

    I have a custom form control component which is as follows:

    @Component({
    selector: 'my-multi-select',
    templateUrl: './multi-select.component.html',
    styleUrls: ['./multi-select.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    providers: [
    {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => MultiSelectComponent),
    multi: true,
    },
    {
    provide: NG_VALIDATORS,
    useExisting: forwardRef(() => MultiSelectComponent),
    multi: true,
    },
    ],
    })
    export class MultiSelectComponent<T = string> extends MyControlValueAccessor<T[]> implements OnInit, OnDestroy, Validator {


    I have implemented a validate method and I want to display an error message within this form control template but I am unsure how to do so: on which property should I retrieve the errors?

    Note that the difficulty here lies in the fact that I am trying to display the error message from within the component's own template as opposed to within an outside form.

    Can someone please tell me on which variable to find the errors property?

    I saw some posts such as: Angular Custom Form Control with Custom Validator Sync Issue or Angular2 custom form control including textfield and error message which recommend introducing a control variable into the component such as:

    • private ngControl: NgControl; or
    • control: AbstractControl

    but I am not sure whether this is good practice. Don't hesitate to comment and advise.

    edit: FYI MyControlValueAccessor implements ControlValueAccessor

    Continue reading...

Compartilhe esta Página