Encountered an error while trying to access the 'touched' property of undefined within Angular6 reactive forms

When attempting to validate my page, I encountered an error stating 'Cannot read property 'touched' of undefined'. Can someone please assist me with this code? Also, feel free to correct any mistakes you may find.

Here is the HTML code:

<div class="container pt-4">
    <form [formGroup]="goalForm" (submit)="submit()">
        <div class="card">
            <div class="card-header">Sub Goals</div>
            <div class="card-body" formArrayName="subgoals">
                <div *ngFor="let goal of goalForm.controls.subgoals.controls; let i=index">
                    <div [formGroupName]="i" class="row">
                        <div class="form-group col-sm-3">
                            <label for="name">Criteria Name *</label>
                            <input class="form-control" formControlName="criteria_name" type="text" 
                                    id="criteria_name" name="criteria_name" 
                                    placeholder="Criteria Name">
                            <span class="text-danger" *ngIf="goalForm.controls['criteria_name'].touched 
                                    && goalForm.controls['criteria_name'].hasError('required')">
                                    Criteria Name is required! </span>
                        </div>                            
                        <div class="form-group col-sm-3">
                            <label for="weightage">Criteria Weightage *</label>
                            <input class="form-control" formControlName="criteria_weightage" type="number" 
                                    id="criteria_weightage" name="criteria_weightage" 
                                    placeholder="Criteria Weightage">
                            <span class="text-danger" *ngIf="goalForm.controls['criteria_weightage'].touched 
                                    && goalForm.controls['criteria_weightage'].hasError('required')">
                                    Criteria Weightage is required! </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>     
    </form>
</div>

kpa-goal.component.ts:

 ngOnInit(){
        this.goalForm = this.fb.group({
            subgoals :this.fb.array([
              this.initgoal(),
            ])
          });
    }
    initgoal(){
        return this.fb.group({
          criteria_name: [null,Validators.compose([Validators.required])],
          criteria_weightage: [null,Validators.compose([Validators.required])]
          });
    }

Answer №1

Within your FormGroup, there was actually a FormArray named subgoals where the two fields, criteria_name and criteria_weightage, were nested inside. To access these fields, you needed to traverse through the subgoals before reaching them.

Here is the relevant HTML code snippet:

<div class="container pt-4">
        <form [formGroup]="goalForm" (submit)="submit()">
            <div class="card">
                <div class="card-header">Sub Goals</div>
                <div class="card-body" formArrayName="subgoals">
                    <div *ngFor="let goal of goalForm.controls.subgoals.controls; let i=index">
                        <div [formGroupName]="i" class="row">
                            <div class="form-group col-sm-3">
                                <label for="name">Criteria Name *</label>
                  <input class="form-control" formControlName="criteria_name" type="text" 
                          id="criteria_name" name="criteria_name" 
                          placeholder="Criteria Name">
                          <span class="text-danger" *ngIf="goalForm.controls.subgoals.controls[0].controls.criteria_name.touched && goalForm.controls.subgoals.controls[0].controls.criteria_name.errors?.required" >
                          Criteria Name is required! 
                          </span>
              </div>                            
              <div class="form-group col-sm-3">
                  <label for="weightage">Criteria Weightage *</label>
                  <input class="form-control" formControlName="criteria_weightage" type="number" 
                          id="criteria_weightage" name="criteria_weightage" 
                          placeholder="Criteria Weightage">
                          <span class="text-danger" *ngIf="goalForm.controls.subgoals.controls[0].controls.criteria_weightage.touched && goalForm.controls.subgoals.controls[0].controls.criteria_weightage.errors?.required" >
                          Criteria Weightage is required!
                          </span>
                        </div>
                    </div>
                </div>
            </div>
        </div>     
    </form>
</div>

You can view a complete working demo on stackblitz here.

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

Using jQuery with Angular 4 allows for powerful front-end development

To include jQuery in an Angular4 project, I follow these steps: npm install --save jquery npm install --save-dev @types/jquery In the app.component.ts file import $ from 'jquery'; or import * as $ from 'jquery'; When running "ng se ...

Is it possible that Angular2 is unable to properly establish the default value when it is selected?

I've been attempting to establish a default value for my selection by using [selected]= "selected_choice == 'one'" similar to this method but unfortunately, it didn't yield the desired result. Upon hearing that [selected] is no long ...

Deactivating Google Map Clustering for Individual Markers

I'm currently utilizing Angular 4, Google Maps v3, and Marker Clusterer v2 - all of which are the latest versions. I'm attempting to implement a straightforward example found in the official Google Maps documentation (https://developers.google.co ...

Implementing an extended interface as an argument in a function

Here is the code snippet for analysis: interface IUserData { FirstName: string, LastName: string, Email: string, Password: string } interface IState extends IUserData { isSuccess: boolean } const state: IState = { FirstName: &apo ...

Setting the height of CKEditor 5: A comprehensive guide

How can I adjust the height of the CKeditor angular component? The documentation suggests we can set the editor style to: min-height: 500px !important; However, this solution does not seem to be effective for me. Any other suggestions? ...

Access a designated webpage with precision by utilizing Routes in Angular

Is it possible to display a different component in Angular routing based on a condition in the Routing file? For example, if mineType is equal to "mino", can I navigate to another component instead of the one declared in the Routing? Should I use Child ro ...

Ways to bounce back from mistakes in Angular

As I prepare my Angular 5 application for production, one issue that has caught my attention is how poorly Angular handles zoned errors. Despite enabling 'production mode', it appears that Angular struggles to properly recover from these errors. ...

The production build for Angular 9 Keyvalues pipe fails to compile

After successfully running my app on the development server with ng serve, I encountered a failure when trying to build it for production. The error message that popped up was: ERROR in src/app/leaderboard/leaderboard.component.html(9,17): Argument of typ ...

The chart is experiencing difficulty printing as it tries to retrieve data from the JSON file

I am currently working on displaying a chart using JSON data, specifically the Volume Sales data stored in an array. JSON: { "year1": { "volumeSales": "0.09", "valueSales": "1.23" }, "year2": { "volumeSales": "0.11", "valueSales": " ...

In Angular 12, encountering the error "Unable to bind to 'formGroup' as it is not a recognized property of 'form'" is not uncommon

Encountering a problem that seems to have been addressed previously. Error: Can't bind to 'formGroup' since it isn't a known property of 'form'. I followed the steps by importing ReactiveFormsModule and FormsModule in the req ...

What is the process for incorporating a custom type into Next.js's NextApiRequest object?

I have implemented a middleware to verify JWT tokens for API requests in Next.js. The middleware is written in TypeScript, but I encountered a type error. Below is my code snippet: import { verifyJwtToken } from "../utils/verifyJwtToken.js"; imp ...

How come validation errors are not appearing on the view?

As I continue to practice, I am working on this form. It successfully displays a console message, indicating the wiring is correct. However, an issue arises when I submit the form without entering any text in the input field, as it fails to show a validati ...

Setting the default date for multiple bootstrap datepickers is a convenient feature that can easily be implemented by

I am working with a dynamically generated table of inputs, where the first column is a date field. To implement the date selection functionality, I am utilizing the bootstrap-datepicker. Each input is functioning correctly as I have given them individual n ...

Issue encountered while declaring a variable as a function in TSX

Being new to TS, I encountered an interesting issue. The first code snippet worked without any errors: interface Props { active: boolean error: any // unknown input: any // unknown onActivate: Function onKeyUp: Function onSelect: Function onU ...

What is the easiest way to choose a child vertex with just one click on mxgraph?

I have nested vertices and I'm looking to directly select the child vertex with just one click. Currently, when I click on a child vertex, it first selects the parent vertex instead. It's selecting the parent vertex initially: To select the ch ...

Preventing the collapse of the right column in a 2-column layout with Bootstrap 3

I've recently begun exploring Bootstrap and am attempting to achieve the following: (Left column - larger) Heading Heading 2 Heading Image Heading Image Heading Address (Right column - smaller) Heading Paragraph List items My issue ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...

The search button in the ngx-pagination StartDate and EndDate Search Filter is unresponsive

Working with Angular-14 and ASP.Net Core-6 Web API to consume an endpoint and handle JSON responses. An example of the endpoint URL without parameters: https://localhost/MyApp/api/v1/all-merchants And when parameters are included: https://localhost/MyApp ...

Using React, PIXI, and Zustand can sometimes lead to stale state issues when handling mouse events

I currently have a Pixi canvas that utilizes pointer handlers. Users are able to click on a point within a 'sequence' and move it. Recently, I came across an issue with the mouse handlers having stale state. To resolve this, I began recreating t ...