When the Angular Reactive form control does not show any errors, it is designated as ng-invalid

Currently, I am working on an (Angular 10) reactive form that includes multiple dynamically-created input components within an ngFor loop. Here is an example of one of these input components:

<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>
<div class="validationFeedback">
    <small *ngIf="this.controlRef?.errors?.required && (this.controlRef?.touched || this.controlRef?.dirty)"
        class="ng-invalid p-invalid">
        {{this.getRequiredFieldValidationMsg()}}
    </small>
</div> 

I have encountered a strange issue where some instances of these components are being incorrectly marked as ng-invalid, despite their FormControl's error property being empty. These affected controls contain valid input and the validation section remains hidden, but they are labeled as ng-invalid. Upon further investigation, I have confirmed that the control contains the correct input and only has the required validator in its rawvalidators property.

If you have any insights into what might be causing this issue or suggestions on how to troubleshoot it further, please let me know!

Answer №1

It appears to be a template-based form structure.

Avoid using ngModel with reactive forms; instead, utilize formControlName for better control. If you encounter side effects, consider subscribing to the valueChanges of the control rather than using (input).

Remember to use patchValue when updating a single input and setValue for updating all values in the form.

Make sure to specify the formGroupName on the parent div of the input element when dynamically creating such structures.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is ConnectionServiceModule not compatible with Angular version 17.2.0?

I have encountered an issue in my Angular project that involves the compatibility of the ng-connection-service library with Angular Ivy. When I attempt to bring in the ConnectionServiceModule from the ng-connection-service into my Angular module, I am rece ...

Creating Typescript types based on the values of other props: A guide

Can the TypeScript prop type be dynamically changed based on the runtime value of another prop? For instance type MyComponent = { propA: boolean | string propB: typeof propA boolean ? number : string } Is it feasible to determine the prop type of p ...

Tips for ensuring the accuracy of email addresses entered?

Within my ASP.NET web form, there is a field designated for entering an email address. The validation process requires that only email addresses conforming to the following pattern are accepted: <a href="/cdn-cgi/l/email-protection" class="__cf_email_ ...

react-hook-form replaces the onChange function causing delays in updating the value

Recently, I created a unique Select component utilizing useState and onChange. I attempted to integrate this custom component with the powerful react-hook-form. Allow me to share the code snippet for the bespoke Select component. const Select = forwardRef ...

Using memoization for React Typescript callback passed as a prop

My component is designed to display data retrieved from a callback provided in the props. To prevent an infinite loop caused by mistakenly passing anonymous functions, I am looking for a method to enforce the usage of memoized callbacks. const DataRenderer ...

Missing expected property in TypeScript casting operation

I recently came across this intriguing playground example outlining a scenario where I attempted to convert an object literal into an object with specific properties, but encountered unexpected results. class X { y: string; get hi(): string { ...

Confirming the data provided in multipart-form after parsing with multiparty and validating using express-validator

I am currently facing an issue where I am sending multipart form data to the server and saving it without any validation. Even though I have implemented multiparty and express-validator for data validation, the data is still being saved without validation ...

Conflicting React types found in pnpm monorepo

In the process of converting an inherited monorepo from yarn+lerna to pnpm workspaces, I am encountering some issues. Specifically, there are mismatching React versions causing errors in typescript. It seems that TypeScript is not recognizing the closest @ ...

Angular2: The NgFor directive is designed to work with Iterables like Arrays for data binding

I'm currently working on a university project to develop a web application consisting of a Web API and a Frontend that interacts with the API. The specific focus of this project is a recipe website. Although I have limited experience with technologies ...

Initial attempt with Angular2 router.navigate() fails to function properly

I have set up the routes as follows: export const routes: Routes = [ { path: '', component: HomeComponent, pathMatch: 'full', canActivate: [AuthGuardService] }, { path: 'sites', component: SiteIndexComponent, resolve: ...

Getter and Setter Implementation in Typescript without Using Classes

Check out these various SO questions discussing Typescript getters/setters: from 2015, Jan 2018, Sept 2018, and more. Now, the question arises - what is the best approach to define Typescript types for getters/setters in a plain JavaScript object without ...

Troubleshooting Typescript app compilation problem in a Docker environment

I am encountering a challenge while trying to build my typescript Express app using Docker. Surprisingly, the build works perfectly fine outside of Docker! Below is the content of my Dockerfile: FROM node:14-slim WORKDIR /app COPY package.json ./ COPY yarn ...

What kind of registration does React Hook Form use?

When utilizing react-hook-form alongside Typescript, there is a component that passes along various props, including register. The confusion arises when defining the type of register within an interface: export interface MyProps { title: string; ... ...

Automatically transitioning from a chatbot interface to an Ionic mobile app page as the conversation progresses

My current setup involves incorporating the MS chatbot-framework V3 into my ionic 3 mobile app using Direct line. The goal is to gracefully end the conversation with the chatbot and seamlessly transition to another page within the mobile app, while also p ...

Why won't my Angular 2 *ngIf display until the function finishes?

Here is the code snippet that I am dealing with... // Pug Template .notification-header-area.layout-row.layout-align-center-center( *ngIf="notification.message != null", class="{{notification.color}}" ) // Inside angular component private onNotificationS ...

Storing data received from httpClient.get and utilizing it in the future after reading

Searching for a solution to read and store data from a text file, I encountered the issue of variable scope. Despite my attempts to use the data across the project by creating a global variable, it still gets cleared once the variable scope ends. import ...

Selecting the correct data type for react-icons

I'm currently working on designing a navigation bar with a customized type to utilize the map() function. My goal is to display an icon for each entity, so that the icon appears in front of the text within the navbar. However, I am encountering diffic ...

How and where should you define the Angular catch all route for handling page not found errors?

In my project, I have a primary app.routing.module.ts with the following configuration: const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'login', component: LoginComponent }, { path: '', re ...

What is the best way to retrieve a cookie sent from the server on a subdomain's domain within the client request headers using getServerSideProps

Currently, I have an express application using express-session running on my server hosted at api.example.com, along with a NextJS application hosted at example.com. While everything functions smoothly locally with the server setting a cookie that can be r ...

Issue encountered while conducting tests with Jest and React Testing Library on a React component containing an SVG: the type is not recognized in React.jsx

In my Next.js 12.1.4 project, I am using Typescript, React Testing Library, and SVGR for importing icons like this: import ChevronLeftIcon from './chevron-left.svg' The issue arises when running a test on a component that includes an SVG import, ...