[Fixed] Angular Reactive form control is marked as ng-invalid when errors property is empty


So I have an (Angular 10) reactive form with a number of input components like this one, each created dynamically in an ngFor loop:

<div [id]="this.getDivElementId()" class="textinput dynControl" [formGroup]="this.parentFormRef" >
    <input [name]="this.controlData.name" [id]="this.controlData.name" type="text" [attr.aria-labelledby]="this.getLabelElementId()" [attr.aria-required]="this.controlData.required" [required]="this.controlData.required" [readOnly]="this.controlData.readOnly" 
         (input)="onValueChange($event)" [maxlength]="this.controlData.maxLength" [placeholder]="this.controlData.placeholder" [pTooltip]="this.controlData.tooltip" pInputText [formControlName]="this.controlData.name">
    <label [for]="this.getLabelElementId()" [id]="this.getLabelElementId()" [attr.data-required]="this.controlData.required">{{this.label}}</label>
<div class="validationFeedback">
    <small *ngIf="this.controlRef?.errors?.required && (this.controlRef?.touched || this.controlRef?.dirty)"
        class="ng-invalid p-invalid">

I have a weird situation in which some of the component instances (but not all) are getting marked as ng-invalid even when the FormControl’s error property is empty. There is valid input in the control, and the validation section stays hidden, but the control itself is marked with ng-invalid. I’ve verified that the form shows the control as having the proper input and the rawvalidators property only shows the required validator.

Any ideas on what might be wrong or how I could further troubleshoot this issue?


Looks like a template driven form.

You shouldn’t use ngModel with reactive forms use formControlName instead if you want a reactive form. And if you have side affects subscribe to valueChanges of the control instead of using (input).

Also when setting a single input use patchValue, when setting the entire form’s values use setValue.

You may need to set the formGroupName on your parent div of the input when creating things like this dynamically.

Leave a Reply

(*) Required, Your email will not be published