Angular throws an error when attempting to access a property that is undefined

I created the following angular template:

<section class="section">
      <div class="container">
        <form [formGroup]="testForm">
          <div class="columns is-multiline">
            <div class="column is-2">
              <div class="box">
                <h1 class="subtitle">Test Array</h1>
                <div formArrayName="salestest" *ngFor="let sale of salestest.controls; let i=index">
                  <div [formGroupName]="i">
                    <div class="field">
                      <label class="label">Test Sale1</label>
                      <div class="control">
                        <input class="input" type="text" placeholder="Sales" formControlName="sales">
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </form>
      </div>
    </section>

This is the associated Component:

export class SalesTestComponent implements OnInit {
  testForm: FormGroup;
  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.testForm = this.fb.group({
      salestest: this.fb.array([this.buildSalesTest()])
    });
    console.log("ngOnint was called");
  }

  buildSalesTest(): FormGroup {
    return this.fb.group({
      sales: ""
    });
  }

   get salestest(): FormArray {
    return <FormArray>this.testForm.get("salestest");
  }
}

Upon running the Angular application, an error is displayed:

ERROR TypeError: Cannot read property 'value' of undefined

The error seems to point to line 3 in the template:

<form [formGroup]="testForm">

It is unclear why Angular is encountering this 'Cannot read property of undefined' error.

The complete error message states:

ERROR TypeError: Cannot read property 'value' of undefined
    at Object.eval [as updateRenderer] (CreateSalesTestComponent.html:23)
    at Object.debugUpdateRenderer [as updateRenderer] (core.js:23838)
    at checkAndUpdateView (core.js:23213)
    at callViewAction (core.js:23449)
    at execComponentViewsAction (core.js:23391)
    at checkAndUpdateView (core.js:23214)
    at callViewAction (core.js:23449)
    at execEmbeddedViewsAction (core.js:23412)
    at checkAndUpdateView (core.js:23209)
    at callViewAction (core.js:23449)

The line referenced in the error is line 23:

ngOnInit() {
    this.testForm = this.fb.group({
      salestest: this.fb.array([this.buildSalesTest()])
    }); <!-- **Line 23** -->
    console.log("ngOnint was called");
  }

Answer №1

There is an error in the following line.

<div [formGroupName]="i">

To correct it, change it to:

<div [formGroup]="sale">

By assigning the index to the formGroupName, the form attribute cannot find the group and its controls within it. You can view a Working Example for reference.

If you encounter any issues, feel free to reach out for assistance. I am here to help.

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

What are the best methods for repairing a malfunctioning Drawer?

My template can be found here: SANDBOX When transitioning to a nested route, I am experiencing a double rendering issue which causes the DRAWER to reopen. How can this be fixed? You can observe this effect in the "NESTED" tab. It is important that the fi ...

Nextjs 13 brings exciting new features, one of which is the ability to call getStatic

I am working on a Next.js 13 application where I have organized my files in the 'app' directory instead of the usual 'pages'. All pages are statically generated during build time and data is fetched from an external API. https://i.sstat ...

Semi-Transparent Photo Slideshow

Currently, I am in the process of developing a Pokedex-like feature for a project that I am working on. The functionality is working as expected, but there is one particular feature that I would like to implement. My goal is to display only certain element ...

angular-cli: Select templates based on the current environment

Currently, I am utilizing @angular/cli: 1.0.0 and aiming to utilize component templates based on the environment. The code implementation is as follows: import {Component} from '@angular/core'; import {environment} from '../environments/env ...

How can I manually transclude content within a directive into two separate locations?

When trying to access the result of ng-repeat, I discovered that using the transclude function and manually compiling could help. However, this method does not work in situations with two places and elements containing ng-repeat. Here is how my code is str ...

There was an error in parsing the JSON data due to an unexpected token "u" at the beginning of the string

I've been working on improving my JavaScript skills, but I hit a snag with an error message that reads "Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse". var requestData = new XMLHttpRequest(); requestData.open('GET& ...

Tips for refreshing the page without losing the values of variables

In my simulation.jsp file, I have the following code that retrieves simulation data from a struts2 action: $(document).ready(function() { var data='<s:property escape="false" value="simInfos" />'; } Once I perform the simulation with this ...

Guide to making a sidebar navigation menu on the left using Bootstrap

How can I create a left navbar using Bootstrap? I managed to do it. <nav class="btn-group-vertical float-left navbar"> <button routerLink="product/home" routerLinkActive="is-active" class="btn btn-outline-dark">Home</button> ...

Guide to accessing the content within an h1 tag with JavaScript

I currently have a setup with 3 pages: 2 of them are WordPress pages while the other page is a custom page template featuring a form. The first two pages were created using the wp-job manager plugin. The first page includes a dropdown menu with a list of a ...

Decorator used in identifying the superclass in Typescript

I am working with an abstract class that looks like this export abstract class Foo { public f1() { } } and I have two classes that extend the base class export class Boo extends Foo { } export class Moo extends Foo { } Recently, I created a custom ...

How can JavaScriptExecutor be used to stop searching for an element on a constantly scrolling interface, such as Facebook, after a specific time period?

Imagine that I am trying to locate my post on a Facebook page by continuously scrolling down. Specifically, I am searching for my post based on my profile name. To achieve this, I utilize JavascriptExecutor to initiate the scrolling process until it locate ...

If the image is not found, deactivate the anchor or hyperlink

I am encountering an issue where I have an image tag within an anchor element setup as shown below: <a href='$image'><img alt='No Image' src='$image'></a> When the image is not available, I can still intera ...

Gulp is ensuring the destination file remains unchanged

I'm encountering an issue with gulp in my project. I've set up a process to automate the compilation of source and styles into a single file using gulp. However, I'm facing a problem where it doesn't want to overwrite the `application.j ...

Error encountered due to an unhandled promise rejection of type

I am currently using async/await to execute a query to the database and receive the result. However, I encountered an error in the browser console that says: Unhandled promise rejection TypeError: "games is undefined" In my code, there are two function ...

When you extend the BaseRequestOptions, the injected dependency becomes unspecified

Implementing a custom feature, I have chosen to extend BaseRequestOptions in Angular2 to incorporate headers for every request. Additionally, I have introduced a Config class that offers key/value pairs specific to the domain, which must be injected into m ...

When viewed on a mobile device, the page defaults to displaying the NumPad instead of the Text Keyboard in Angular

The email field in my angular app is opening a Key Pad in mobile view and I'm not sure why. <form (ngSubmit)="onSubmit()" #emailForm="ngForm"> <div class="emailaddress" style="text-align:center;" *ngIf="!showEmail"& ...

arrange the elements in a specified sequence

I am trying to sort an array in a specific order var customOrder = { "1st Presentation / Meeting": 0, "Follow-On Meetings": 1, "Hold\/Uncategorized": 2, "MGL": 3, "PGL": 4, "BGL": 5, "RGL": 6, "SGL": 7, "Uncategorized Leads": 8, ...

The jQuery .on("change") function keeps triggering repeatedly, but I'd like it to only execute once

I'm currently working on a feature that involves detecting changes to input text fields. Every time the user makes a change in an input field, I need to capture the new value and validate it. However, I've noticed that the code I have implemented ...

Angular 5 does not allow function calls within decorators

I encountered an issue while building a Progressive Web App (PWA) from my Angular application. When running ng build --prod, I received the following error: ERROR in app\app.module.ts(108,64): Error during template compile of 'AppModule' Fu ...

The onClick function within the .map function is continuously triggered

I am encountering an issue with my code where a Dialog confirmation prompt from Material UI keeps getting called unexpectedly. The problem seems to arise when I add a value to the function that is triggered by a button click within a loop of an array usi ...