Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set input invalid inside custom form control in Angular 2

Tags:

angular

I have created a custom autocomplete form control, that implements ControlValueAccessor and Validator and integrated it successfully into a reactive form. The input element inside the custom form control uses ngModel.

The value of the form component is valid, if the object returned by it contains a numeric ID.

For example { id: 1, name: 'Test' } would be a valid object.

Everything is working fine, but unfortunately the input element has the ng-valid CSS class applied to it, since it is not part of the reactive validation process (it uses ngModel).

The input element has my own appInput directive applied to it, so I have access to all form related classes like NgControl, or FormGroupDirective.

This is my custom autocomplete template:

<input
    #searchTerm
    appInput
    type="search"
    [ngModel]="name"
    (ngModelChange)="keyupSubject.next($event)"
/>

and it is inside a reactive formGroup:

<div [formGroup]="parentFormGroup">
    <div class="col-sm-11">

        <app-autocomplete
            formControlName="name">
        </app-autocomplete>

    </div>
</div>

I have tried ngControl and setErrors inside my appInput directive, but the CSS class is still not set.

@Input()
set errors(errors) {
    const control = this._ngControl;
    control.control.setErrors(errors);
}

How do I set the input element inside my custom form control invalid? I am asking specifically about the CSS class ng-invalid on the input element.

like image 412
Alexander Ciesielski Avatar asked Nov 08 '22 18:11

Alexander Ciesielski


1 Answers

In your control get the NgControl

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

Then in your view you can bind any elements to the validity on ngControl:

<input [ngClass]="ngControl?.valid ? 'ng-valid' : 'ng-invalid'" class="form-control" />
like image 139
Cirem Avatar answered Nov 14 '22 22:11

Cirem