Encountering an error when trying to extract value from an array containing formArray elements

My goal is to create a form array within an array for master detail use. I have defined the structure as follows:

  agreementForm: FormGroup;
  agrArr: any[] = [];

  constructor() {
    this.agreementForm = new FormGroup({
      serviceArr: new FormArray([])
    });
  }

  submitAgreement() {
    const data = this.agreementForm.value;
    this.agrArr.push(data);
  }

  submitForm() {
    console.log(this.agrArr);
    for(i=0;i<this.agrArr.length;i++) {
      for(j=0;j<this.agrArr[i].serviceArr.length;j++){
        console.log(this.agrArr[i].serviceArr[j]);
      }
    }
  }

Initially, I can view the entire agrArr on the console but encounter an error when looping through the nested arrays. The error message displayed is:

ERROR TypeError: Cannot read properties of undefined (reading 'serviceArr')

Upon further investigation, individual elements of agrArr also return undefined values. This inconsistency arises after successfully retrieving the complete array initially. How do I troubleshoot this issue and properly access elements within both arrays?

Answer №1

One must ensure that the array is defined and has a size greater than zero before using the find method.

Consider this approach:

submitForm() {
    console.log(this.agrArr);
    for(i=0;i<this.agrArr.length;i++) {
      if (this.agrArr[i].serviceArr && this.agrArr[i].serviceArr.length > 0) {
        for(j=0;j<this.agrArr[i].serviceArr.length;j++){
          console.log(this.agrArr[i].serviceArr[j]);
        }
      }
      
    }
}

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 function 'Subscribe' does not work properly in Angular when used with Socket.IO

I'm currently developing a chat application that utilizes a Node server with socket.io on the server side and Angular along with socket.io-client on the client side. However, I've encountered an issue where I receive a "this.socketService.getMess ...

Ionic 4 FormBuilder fails to recognize automatically filled data retrieved from database during submission

I am brand new to working with Ionic. I've set up an ionic form with ReactiveFormsModule and FormsModule initialized in edit-profile.page.module.ts, with the intention of updating a user's profile information. However, despite filling out all the ...

Is it possible to generate a Date object from a predetermined string in typescript?

I have a string with values separated by commas, and I'm trying to create a Date object from it. It seems like this is not doable -- can someone verify this and provide a solution if possible? This code snippet doesn't work : let dateString=&a ...

Achieve a new version without relying on conditions

I am looking to achieve the same functionality as the code below but without using any condition statements. HelloFunction(x){ If(x<0){ Console.log("greater"); }Else{ Console.log("smaller"); } }; HelloFun ...

Struggling to successfully map angular model data to a Spring POJO class

I am currently having issues mapping an Angular model class to my Spring model class. When I try to do so, all the entities in the Spring model class show up as null. I have included the code snippets below that I used for mapping, but unfortunately, it fa ...

Establishing the link between Angular 7 and Firebase Storage

I am trying to fetch a photo from firebase storage in Angular 7, but I am encountering an error that I can't resolve. Below is the code snippet: app.module.ts import { AngularFireModule } from 'angularfire2'; import { AngularFireStorageMo ...

Asserting within a specific condition's scope in TypeScript

I am facing a similar situation, type Field1Type = { a: string; } type Field2Type = { b: string; c: number; } type ObjType = { field: Field1Type | Field2Type } const field = { b: "" c: 0 } const obj = { field } as ObjType i ...

Determine the presence or absence of data in an Angular Observable

Here is an example of how I am making an API call: public getAllLocations(): Observable<any> { location = https://v/locations.pipe(timeout(180000)); return location; } In my appl ...

Angular checkbox utilizing an off-screen input element

Having an issue with Angular checkbox and would greatly appreciate any help: HTML: <span for="check" tabindex="0" role="checkbox" (click)="inputCheck.click()" (keydown)="keyEvent()"> <label for="check">checkbox</label> <input ...

Exploring the activatedRoute observables with rxjs operators

I am seeking assistance with a straightforward task: I want to explore the activateRoute observables (both paramMap and queryParamMap) - I aim to adjust component variables based on their values. I attempted to achieve this using rxjs operators pipe and ...

Guide to Displaying Individual Observable Information in HTML with Ionic 3

When using Observable to retrieve a single object from Firebase, how can I display this data on an HTML page? I attempted to use {{(postObservable2|async)?.subject}}, but it does not render. Another approach involved AngularFireObject, yet it resulted in ...

Guide to adding a class to dynamically generated Angular Material elements

Regarding a previous discussion on Stackoverflow, where there was an attempt to target the dynamically rendered Angular Material component class cdk-overlay-container through a class selector using a directive. The main objective was to add a specific clas ...

Combining data from various API calls into one cohesive array using RXJS

My RXJS Pipeline is structured as follows: const logs: number[] = [1, 2, 3, 4]; const url = 'http://some-url-here.com'; const pipeline = from(logs).pipe( switchMap(logId => this.callEndpoint(url, logId).pipe(map(response => response. ...

The HttpClient.get('/') request with {observe: 'response'} is failing to retrieve some headers

Currently, I'm in the process of writing an API GET request by utilizing HttpClient.get(). Upon passing in the option to observe the response, I've encountered an issue where accessing the .keys() does not provide me with any headers apart from C ...

Tips for submitting a form using a button located outside of a form tag dynamically

I've created a multi-step form with a "next" button to navigate through different steps. On the final page, it transitions to a "submit" button that connects to a form. For this transition, I dynamically set the type and form attributes on the button ...

Challenges arise when integrating Angular with Firebase, particularly in the realms of authentication and user

Currently, I am working on a project using Angular and Firebase. However, in the auth.service.ts file, Visual Studio Code is not recognizing the imports for auth and User. import { auth } from 'firebase/app'; import { User } from 'fireba ...

Ways to update a component upon becoming visible in Angular

Within my Angular 4.3.0 project, the header, left panel, and right panels are initially hidden on the login page until a successful login occurs. However, once they become visible, the data is not pre-loaded properly causing errors due to the ngOnInit meth ...

Testing the selection of dropdown values in Angular2 using unit tests

I have a dropdown menu for selecting countries. It defaults to a pre-selected value, and when the user changes it, they are redirected to the corresponding country page. However, I am facing an issue while trying to unit test the default value in the sele ...

SystemJS is responsible for loading a multitude of files related to rxjs

After finding an example on the internet, I have created my own systemjs.config.js: (function (global) { System.config({ paths: { // paths serve as alias 'js:': 'js/', }, // map tells ...

Dynamic side menu change in Ionic 3 allows for flexibility and customization in the app's

Is there a way to automatically change the direction of the side menu when switching between languages (rtl and ltr)? I attempted to implement this functionality in the app.html page using the following code: <ion-menu [side]="isRtl?'right':& ...