Struggling to dynamically create form controls within Angular forms and receiving the following error in the console: "TypeError: feature_r5.get is not a function"

When I click a button in my Angular v14 HTML template, I am trying to dynamically generate form controls and although I am able to generate them, an error is popping up in the console.

ERROR TypeError: feature_r5.get is not a function
 at PostAdvComponent_div_40_Template

Here is the HTML template code:

<div id="features" class="tab-pane mytab-pane">
            <div class="form-group">
                <button type="button" class="btn btn-primary" (click)="addFeatureButtonClick()">Add</button>
            </div>

            <div formArrayName="features" *ngFor="let feature of advForm.get('features')?.value; let i = index">
                    <div attr.formGroupName="{{i}}">
                        <div class="form-group" [ngClass]="{'has-error' : feature.get('fName').invalid &&
                                                                           feature.get('fName').touched}">
                            <div class="input-group">
                                <span class="input-group-prepend">
                                    <label class="input-group-text"><strong>Features</strong></label>
                                </span>
                                <input type="text" id="{{'fName'+i}}" name="fName" class="form-control" placeholder="Features"
                                    formControlName="fName"/>
                            </div>
                            <span class="help-block" *ngIf="feature.get('fName').errors.required &&
                                                            feature.get('fName').touched">
                                Feature is required
                            </span>
                        </div>
                    </div>
            </div>
        </div>

Answer №1

  1. Avoid iterating over the values directly (if you change an input, Angular will redraw and you'll lose focus):

    *ngFor="let feature of advForm.get('features')?.value;.." //<--INCORRECT
    

    Instead, use a "getter"

    get featureFormArray()
    {
       return this.form.get('features') as FormArray
    }
    

    and iterate over the "controls"

    *ngFor="let feature of featureFormArray.controls;.." //<--CORRECT
    
  2. formGroupName is not just an attribute, it's a directive:

    <div attr.formGroupName="{{i}}"> //<--INCORRECT
    <div [formGroupName]="i"> //<---CORRECT
    
  3. When managing formGroup of formArray, consider this structure: (formArrayName outside loop, same tag in loop, formGroupName)

    <form [formGroup]="form">
       <div formArrayName="features">
          <div *ngFor="let feature of featuresFormArray.controls;let i=index"
                       [formGroupName]="i">
             ...your inputs...
             <input formControlName="fName">
          </div>
       </div>
    </form>
    
  4. Use the safe operator (?) after .get to avoid errors like "possible null or undefined"

    feature.get('fName')?.invalid && feature.get('fName')?.touched
    
  5. Similarly, when checking for errors.required

    *ngIf="feature.get('fName')?.errors?.required
    

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

.toggle function malfunctioning

Upon page load, I have a script that toggles the County menu. The goal is to hide the county menu if any country other than "United Kingdom" is selected on page load. If the user selects another country after the page has loaded, there is an issue where ...

AngularJS allows a function to return an array value, which can be displayed in separate blocks on

Building a program that involves working with an AngularJS array. I need to showcase the elements of the AngularJS array, returned by a function, in an organized manner. Each element should be displayed correspondingly - for example, 'first' cont ...

The authentication0 router fails to initiate navigation

I'm currently using Auth0 in combination with Angular 2. The issue I am encountering is that my login code isn't redirecting to the home page after authentication. Based on my understanding, Auth0 does not handle the redirection process itself. ...

Is there a way to deactivate the <script> tag using CSS specifically for media queries?

When designing a website exclusively for desktop usage, I encountered the issue of it not being viewable on mobile devices. I attempted to address this problem by utilizing the code below: script { display: none; pointer-events: none; } Unfortunat ...

Are the props.children handled differently within the <Route> component compared to other React components?

Each and every react component undergoes a process in the following function, which is located in ReactElement.js within node_modules: ReactElement.createElement = function (type, config, children){ . . . } This function also encompasses <Rou ...

Using jQuery, you can easily pass an array in an AJAX request

I am working on a form that has multiple identical fields: <input type="text" id="qte" value="" name="qte[]"> How can I pass the array to my file processing? I have observed that the array sent via ajax is converted into a string. $("#form_comman ...

Accessing a variable from an external JavaScript file using jQuery

Can someone help me out with this issue I'm facing? I am having trouble getting a string returned to a variable in my embedded Javascript code. token.js: function token () { return "mysecretstring"; } HTML Code: <!DOCTYPE html> <h ...

Encountering a Vercel deployment failure due to a TypeError: The 'split' property cannot be read from undefined within several objects

I'm having trouble deploying my web application for the first time and encountering this error on Vercel: TypeError: Cannot read property 'split' of undefined at Object.3qS3 (/vercel/path0/.next/serverless/pages/[collection]/[templateId].j ...

Issue with overlay functionality after updating to jQuery version 1.12.1

Hey there! I'm currently in the process of upgrading my web application system's jQuery to version 1.12.1 and I've run into an issue with the overlay not functioning properly in the new jQuery version. My setup involves using ajax to displ ...

Decorators do not allow function calls, yet the call to 'CountdownTimerModule' was executed

While building production files, the aot process is failing with this error message: Function calls are not supported in decorators but 'CountdownTimerModule' was called. I run the build command using npm run build -- --prod --aot and encounter ...

Challenge with maintaining tab view data in Openui5

I am facing an issue with my application's tabs. Each tab renders data retrieved through ajax calls from the database. However, whenever I switch between tabs, the data gets refreshed each time. Is there a way to prevent this refreshing behavior and i ...

Is there a way to trigger an Ajax function after individually selecting each checkbox in a list in MVC 4 using Razor syntax?

Is it possible to trigger an AJAX function when a checkbox within the ul below is checked? Each checkbox has a unique name attribute, such as chkbrand_1, chkbrand_2, chkbrand_3, etc. I am able to obtain the correct value using this code: $('.sear ...

How can the callback from C++ be successfully installed in the Javaobject window within QtWebkit?

I have successfully implemented HTML-JS to call a C++ method using QtWebkit. Now, I want to send a callback from the C++ method to the JavaScript window. How can I achieve this? Below is my code snippet. #include <QtGui/QApplication> #include <Q ...

Is it feasible to execute a cross-site request forgery attack on a URL that delivers a JSON object as a response?

I am aware of the potential for a Cross-Site Forgery Attack that can target requests returning arrays by manipulating the Array constructor. For instance, let's say I have a site with a URL: foo.com/getJson that provides the following array: [&apos ...

Unable to load the threejs module

I am still learning about threejs and have mostly worked on projects using a dev server (vite) locally. This setup limited me to accessing my projects only from the browser on my computer. Here is how I typically include my files in these projects: <bod ...

Simplified jQuery function for multiple div mouseover operations

Uncertain about the accuracy of my title. Due to certain reasons, I need to assign different IDs for the class, as it only detects ID and not class when hovered over. Therefore, I have created a CSS version where the opacity of a specific div will change t ...

How can I handle a queue in Angular and rxjs by removing elements efficiently?

I'm facing a challenging issue with my code that I need help explaining. The problem lies in the fact that a function is frequently called, which returns an observable, but this function takes some time to complete. The function send() is what gets c ...

Using Django to load a template and incorporate a loading spinner to enhance user experience during data retrieval

In my Django project, I need to load body.html first and then dashboard.html. The dashboard.html file is heavy as it works with python dataframes within the script tag. So, my goal is to display body.html first, and once it's rendered, show a loading ...

Angular template variables in VS Code now have the ability to automatically update their names when renamed

Here is a snippet from the controller: /* Local copies of Enumerators to use on template */ MeasurementOriginEnum: typeof MeasurementOriginEnum = MeasurementOriginEnum; And here is how it is used in the template: <button *ngIf="element.getMeasure ...

React 18 doesn't trigger component re-rendering with redux

In my code, I have implemented a custom hook to handle global data fetching based on user authentication. Here is an example of the hook: const userState = useSelector(state => state.user.state) useEffect(() => { if(userState === "authentic ...