Issue with form control validation within a form array not functioning as expected

I am working with a form array that contains form controls.

Here is the snippet of HTML code:

<div class="container">
                            <ng-container formArrayName="positions">
                                <div class="row" style="margin-top:20px;"
                                    *ngFor="let _ of positions.controls; index as i">
                                    <ng-container [formGroupName]="i">
                                        <div class="col-sm flex-3">
                                            <input class="form-control" trim-directive formControlName="name"
                                                maxlength="64" />
                                            <div class="has-danger"
                                                *ngIf="form.get('name').touched || form.get('name').dirty">
                                                <div *ngIf="form.get('name').errors?.required"
                                                    class="form-control-feedback">
                                                    {{'FieldIsRequired' | localize}}
                                                </div>
                                            </div>
                                        </div>

                                    </ng-container>
                                </div>
                            </ng-container>
                        </div>

This is how I define it in the TypeScript file:

createForm(): any {
    this.form = this._formBuilder.group({
        positions: this._formBuilder.array(
            [
                this._formBuilder.group({
                    recruitmentAgencyClientId: [this.recruitmentAgencyClientId],
                    loanAmount: ['', [Validators.required, Validators.min(2000)]],
                    name: ['', [Validators.required]]
                })
            ], Validators.required)
    });
    this.getPositionsCount();
    this.getTotalLoanAmount();
}

However, when I attempt to run the project, I encounter the following error:

TypeError: Cannot read property 'touched' of null

This error occurs at the line

*ngIf="form.get('name').touched || form.get('name').dirty"

Any suggestions on how to resolve this issue?

Answer №1

form is the main form group. To access the inner form group, you need to follow these steps:

<div class="container">
    <ng-container formArrayName="positions">
        <div class="row" style="margin-top:20px;"
            *ngFor="let innerForm of positions.controls; index as i">
            <ng-container [formGroupName]="i">
                <div class="col-sm flex-3">
                    <input class="form-control" trim-directive formControlName="name"
                        maxlength="64" />
                    <div class="has-danger"
                        *ngIf="innerForm.get('name').touched || innerForm.get('name').dirty">
                        <div *ngIf="innerForm.get('name').errors?.required"
                            class="form-control-feedback">
                            {{'FieldIsRequired' | localize}}
                        </div>
                    </div>
                </div>

            </ng-container>
        </div>
    </ng-container>
</div>

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

The error code TS2345 indicates that the argument '{ read: typeof ElementRef; }' cannot be assigned to the parameter '{ read?: any; static: boolean; }'

Currently in the process of updating my Angular application from version 7 to version 8. Upon running ng serve, I encounter the following error: Error TS2739: Type '{}' is missing the following properties from type 'EmployeeModel': stat ...

Is it possible to create a return type structure in TypeScript that is determined by the function's argument?

I'm currently stuck on developing a function that takes a string as an argument and outputs an object with this string as a key. For example (using pseudo code): test('bar') => {bar: ...} I am facing difficulties in ensuring the correct ...

Is it possible to extend the String prototype with the forEach method as found in the Array prototype?

It is common knowledge that there is a .forEach() method for arrays in JavaScript, but unfortunately Strings do not have that method integrated. So, the question arises: is it problematic to use the following code snippet: String.prototype.forEach = Array ...

What is the best way to create all possible combinations of key-value pairs from a JSON array?

In my scenario, there is a JSON array with key-value pairs where the values are arrays. Here's an example: json = {foo:[1,2],bar:[3,4],pi:[5]} I am looking for a way to generate all possible combinations of these parameters for any number of keys. Th ...

Sharing information through a hyperlink to a Bootstrap popup window

I've been attempting to send data to a Bootstrap modal window with no success so far. First, I tried: <a href="#TestModal?data=testdata" role="button" class="btn" data-toggle="modal">Test</a> However, the modal did not open as expected. ...

Error occurs when implementing Google login in React, happening both during rendering and after successful sign-in

Hey there! I recently started using React-Google-Login to implement a sign-in button on my project. I followed the documentation closely, but unfortunately ran into 2 errors while testing it out. Here's the code snippet I currently have: import Goog ...

The quirks of JSON.stringify's behavior

I am in the process of gathering values to send back to an ASP.NET MVC controller action. Despite using JSON.stringify, I keep encountering Invalid JSON primitive exceptions and I am unsure why. I have a search value container named searchValues. When I i ...

Unable to remove the white space appearing below and after a div in HTML

I have been working on creating a website. You can find my JSFiddle here. On my JSFiddle, you might notice a white gap above the black image labeled INSURANCE, and another white gap below it. I've tried various solutions but haven't been able to ...

Attempting to keep a:active state active until another link is clicked

My goal is to have two links, "hot" and "update." When "hot" is clicked, it should turn red and "update" should turn black. Conversely, when "update" is clicked, it should turn red and "hot" should turn black. This functionality works perfectly on a Fiddl ...

What is the best way to create height segments from a cylinder in three.js?

My current project involves a cylinder that is divided into multiple height segments, with the number of segments depending on the specific data. Each height segment contains a value that I want to use for extruding the entire circle at that particular hei ...

What could be the reason for the variance in behavior of this function when called for the first and second time in React js

I am currently working on integrating turn-by-turn navigation using mapbox gl js in a react application. My goal is to make the marker's position update smoothly instead of it instantly teleporting. To achieve this animation effect, I have implemented ...

obtain the selected value from the radio button

While working on the server side, I dynamically created radio buttons with the following code: RadioButton button1 = new RadioButton(); button1.ID = question.Name + "_Radio1"; button1.Text = "Yes"; RadioButton button2 = new RadioButton(); button2.ID = qu ...

Validating Input Field with Regular Expression in JavaScript/TypeScript to Avoid Starting with Zero

I need to create a RegEx for a text field in Angular / TypeScript that limits the user to inputting only a 1-3 digit number that does not start with 0. While it's straightforward to restrict input to just digits, I'm struggling to prevent an inpu ...

Having trouble launching the application in NX monorepo due to a reading error of undefined value (specifically trying to read 'projects')

In my NX monorepo, I had a project called grocery-shop that used nestjs as the backend API. Wanting to add a frontend, I introduced React to the project. However, after creating a new project within the monorepo using nx g @nrwl/react:app grocery-shop-weba ...

How can I create a clickable <div> element containing multiple links and trigger only one action?

Within my code, there is a <div> element that has been made clickable. Upon clicking this <div>, the height and text expand using the jQuery function $(div).animate();. While this functionality works as intended, I am encountering a slight issu ...

Discovering the file names of JavaScript files within a context path and dynamically loading them

I am currently working on a Struts application where I need to dynamically load a JSP file with its corresponding JavaScript file upon menu selection. Although the functionality is working smoothly, I am facing an issue in loading the JavaScript file along ...

Is there a way to check for keys in a TypeScript object that I am not familiar with?

I have a good understanding of the unknown type in TypeScript. I am dealing with untrusted input that is typed as unknown, and my goal is to verify if it contains a truthy value under the key input.things.0. function checkGreatness(input: unknown) { retu ...

When utilizing JavaScript's split method, an empty string returns an array size of one instead of zero

Is there a way to separate a string using commas to create an array in Node.js? exports.test = function(rq, rs){ var mailList = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="16657e7764777856627365623875797b">[email ...

What is the best way to differentiate between several elements inserted via JavaScript in my HTML code?

I'm attempting to replicate the image below using HTML and JavaScript: https://i.sstatic.net/kvmqk.jpg So far, this is what I have: https://i.sstatic.net/8iHfB.png Here's my JavaScript code: function createLink(text, parentElement) { var ...

When the network connection is active, the observable will retry and repeat based on other observable signals

Sample snippet: const networkConnected = new BehaviorSubject<boolean>(false); setTimeout(networkConnected.next(true), 10000); webSocket('ws://localhost:4949') .pipe( retryWhen(errors => errors.pipe(delay(10000), filter(() => n ...