What could be causing FormArrayName to consistently display as undefined in my HTML code, even when the safe-navigation operator is employed

Currently, I'm referring to the Angular Material example found at https://angular.io/api/forms/FormArrayName

Upon initializing the packageForm formGroup in ngOnInit() and logging it in the console during ngAfterViewInit(), I can see that the translations FormArray is present. However, when trying to access it in the HTML, I encounter an undefined error. Even after using a safe-navigation operator on the formArray, the issue persists with nothing being displayed.

Below is the code snippet from the component.ts file:

ngOnInit() {
    this.packageModel = this.activatedRoute.snapshot.data['package'];
    if (this.packageModel) {
      this.editting = true;
    } else {
      this.packageModel = new PackageModel(null, true, 1, 0, 0, []);
    }
    this._setupForm();
  }

  ngAfterViewInit() {
    console.log(this.packageForm)
  }

  private _setupForm() {
    this.packageForm = this.formBuilder.group({
      isActive: [this.packageModel.isActive, [Validators.required]],
      quantity: [this.packageModel.quantity, [Validators.required]],
      minPrice: [this.packageModel.minPrice, [Validators.required]],
      maxPrice: [this.packageModel.maxPrice, [Validators.required]],
      translations: this.formBuilder.array([
          this._createTranslationFormGroup(0),
          this._createTranslationFormGroup(1)
      ])
    });

    console.log(this.packageForm)

    this.packageForm.get('isActive').valueChanges.subscribe(value => {
      this.packageModel.isActive = value;
    });
  }

  private _createTranslationFormGroup(index: number) {
    return this.formBuilder.group({
      name: [this.packageModel.translations[index].name, [Validators.required]],
      description: [this.packageModel.translations[index].description, [Validators.required]]
    });
  }

Here is the corresponding HTML code snippet:

<div *ngIf="packageForm" class="package-form" [formGroup]="packageForm">
    <div formArrayName="translations">
        <div class="row" *ngFor="let translation of translations.controls; index as i" [formGroupName]="i">
            <div class="col-6">
                <mat-form-field>
                    <input type="text" matInput [formControlName]="name" />
                </mat-form-field>
            </div>
        </div>
    </div>
</div>

The error message received states: ERROR TypeError: Cannot read property 'controls' of undefined

Please refer to this screenshot for visualization: https://i.sstatic.net/cIoFE.png

Thank you in advance for your assistance!

Answer №1

Remember to use

*ngFor="let translation of packageForm.get('translations').controls
when iterating through translations in Angular. A common practice is to create a getter function in the component for easier access.

get translations() {
 return this.packageForm.get('translations') as FormArray
}
^^ By using this getter function, your template references will be correct.

In addition, remember that

<input formControlName="name">
does not require braces around it.

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

Instantiate a fresh object using the new keyword followed by the Class constructor, and if desired,

I'm looking for a class that I can easily create new instances from and optionally assign properties using the constructor. For instance: class Person { name: string; age: number; constructor(props: {name?: string, age?: number}) { this.nam ...

What is the correct way to exclude and remove a portion of the value within an object using TypeScript?

The function useHider was created to conceal specific values from an object with the correct type. For example, using const res = useHider({ id: 1, title: "hi"}, "id"), will result in { title: "hi" } being returned. Attempting ...

Only JSON objects with a boolean value of true will be returned

I am working on returning JSON objects in JavaScript/TypeScript that have a true boolean value for the "team" property. For example, the JSON data I am using is as follows: { "state": "Texas", "stateId": 1, "team": true }, { "state": "Cali ...

Error in the design of PrimeNg calendar rendering in Angular 2

I have implemented the primeNg module from primefaces in Angular 2 to create a timepicker. It seems to be working, but the design appears broken. Is there something else I need to add to correct the design? Below are the versions of the packages I used: P ...

Switch out bootstrap icons for angular material icons

I'm currently in the process of transitioning from using Bootstrap to Angular Material in an existing application. I need assistance with replacing the Bootstrap icons with Angular Material icons. Any help is greatly appreciated. <md-button class= ...

Encountering a 500 error (Internal Server Error) while trying to connect API Laravel 5.4 with Angular 2

Every time I try to submit a form from an Angular form to my API built on Laravel, I encounter a 500 error (Internal Server Error) in the console. What could be causing this issue? Note: The backend API functions perfectly when tested with POSTMAN. This ...

Ways to showcase corresponding information for an item contained within an array?

I'm working with a function that is designed to retrieve specific descriptions for objects nested within an array. The purpose of the function (findSettings()) is to take in an array (systemSettings) and a key (tab12) as arguments, then use a switch s ...

Are you ready to dive into the world of running an ASP.NET MVC project with Angular in Visual Studio

Currently, I am working on developing a CRUD application using ASP.NET MVC in Visual Studio with Angular. I am interested in running the entire project solely through VS Code without relying on Visual Studio. Does anyone have a solution for achieving thi ...

What is the process for clearing cache in inversifyJS?

In my simple application, I am using express server along with TypeScript. Initially, I can successfully reach my endpoint, but after updating the model, the old data persists. I have attempted the suggested approach mentioned here: How to disable webpage ...

Encountering a problem during the installation of Angular 4

I'm encountering issues during the installation of the @angular/cli package. Currently, my node version is v6.11.2 and npm version is 5.3.0. My first attempt to install it using sudo npm install -g @angular/cli resulted in an error message that kept ...

Organizing the AuthGuard(canActivate) and AuthService code in Angular 2

After working on my current code, I have encountered an issue when routing to a page with the canActivate method. I was able to retrieve authentication data from the server using the following setup auth.guard.ts (version 1) import { CanActivate, Activat ...

Develop a personalized Angular module utilizing ngx-translate functionality

I recently developed my own personal Angular library filled with various components to streamline my projects. I followed a helpful tutorial to create the library successfully. Testing it in another project went smoothly. Now, the challenge is incorporati ...

Verifying callback type in Typescript based on another argument's validity

There is a JavaScript function that I am working with: const fn = (cb, param) => { cb(param); }; This function is meant to be called in two ways within TypeScript: const cb0 = () => {}; fn(cb0); const cb1 = (param: string) => { }; fn(cb1, &a ...

Is there a method to incorporate lists of varying types in a single v-for loop without causing any issues with type validations?

My current component is designed to display two different datasets, each with their own unique nature of data: state.articleTypeList: string[] state.renderPriceClassNameList: {[key: string]: string[]} To render both datasets within a single v-for componen ...

Encountering a service call error during the execution of Angular 2 unit tests using Jasmine

Struggling with testing an angular service, my TypeScript code seems correct but I keep getting an error in my test cases for "this.someFunction.show()" not being a function, even though it exists in my actual service. Here is what I'm attempting to d ...

Is it possible for NodeJS to redirect to an Angular5 route and return JSON instead of a webpage?

When using the API, I'm attempting to redirect a user if it is detected that they are no longer logged in. For example, if a user initiates an action (PUT) to the api, the API verifies the user's status. If the user is logged in, the action is ca ...

Tips for tidying up duplicated typescript content sourced from a pre-existing library

Seeking guidance on implementing best practices and gaining a better understanding of my approach. After discovering the library react-google-calendar-api, I successfully installed it using npm in my React project. However, I wanted to expand its function ...

Overriding default styles in an Angular component to customize the Bootstrap navbar

Is there a way to alter the color of the app's navbar when a specific page is accessed? The navbar is set in the app.component.html file, and I am attempting to customize it in a component's css file. app.component.html <nav class="navbar na ...

Retrieve class property in Angular by its name

How can I retrieve an array from a class like the one below without using a switch statement, dictionary, or other collection to look up the name passed into the method? export class ProcessOptions { Arm = [{ name: 'Expedited Review ("ER") ...

Next.js page freezes when Axios request is made causing the tab to become unresponsive

Curious about how to troubleshoot (or where to start) with my current Axios problem. I am working on a Next.js project (12.3) and have an axios interceptor hook that manages all of my internal requests. The interceptor functions properly on every action/pa ...