"Dynamically incorporating form inputs into a reactive form in Angular: A step-by-step

I recently completed a tutorial on reactive forms in Angular from . I followed the steps to create a nested form, similar to what was shown in the video. However, I am facing an issue with generating a formarray upon button click. Despite no errors being displayed, the inputs are not showing up as expected. I have compared my code multiple times with the tutorial and everything seems identical. Can someone take a look and point out where I might be going wrong?

Here is a snippet of the TypeScript code used to generate the form:

ngOnInit() {
    this.materialAddForm = this.fb.group({
        article_seller_id: '',
        informationNote: '',
        buildMaterial_sellers: this.fb.array([
          ]),
        materialCode: '',
        materialName: '',
        materialType: '',
        material_image_url: '',
        material_prices: '',
        quantity: '',
      }
    )
  }

  get sellerForm(){
    return this.materialAddForm.get('buildMaterial_sellers') as FormArray
  }
   addSellerForm(){

    const sellerForm = this.fb.group({
      name: []
    })
     this.sellerForm.push(sellerForm)

  }

Below is the HTML code that generates the dynamic form:

<div class="-pull-right">
                    <button type="button" (click)="addSellerForm()" class="btn btn-primary mb-2">Add Seller</button>
                  </div>

    <div formArrayName="buildMaterial_sellers">
                <div *ngFor="let seller of sellerForm.controls let i=index" [formGroupName]="i">
    
                  <div class="input-group input-group-sm col-12 col-md-6 mb-4">
                    <div class="input-group-prepend">
                      <span class="input-group-text" id="name">Seller Name</span>
                    </div>
                    <input type="text" class="form-control" aria-label="Sizing example input"
                           aria-describedby="inputGroup-sizing-sm"
                           formControlName="name" >
                  </div>
    
                </div>
              </div>

Answer №1

When adding elements to a form array, make sure you are pushing the correct types. If you push an empty form group instead of a form control, the template may not be able to access the control by name. To avoid this issue, consider pushing {name: this.fb.control()} instead. It's important to only add the ReactiveForm type that corresponds to what you want in the array. Adding a form group instead of a form control is a valid pattern, but it might not achieve the desired outcome.

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 object in TypeScript to reduce arrays

Is there a way to set the return value for my reducer in TypeScript? I am looking to achieve: Instead of using 'any', what should I assign as the type for acc? How can I define my return type so that the output will be {temp: 60, temp: 60}? retu ...

Troubleshooting Missing Exports from Local Modules in React Vite (Transitioning from Create React App)

I have encountered an issue while trying to import exported members from local nodejs packages in my project. Everything was working fine with the standard CRA webpack setup, but after switching to Vite, I started getting the following error: Unca ...

Fix for sorting issue in Angular 4.4.x mat-table header

I am facing an issue with my mat-table sorting header. I have followed the examples and decorated the columns accordingly: <ng-container matColumnDef="id"> <mat-header-cell *matHeaderCellDef mat-sort-header> Id </mat-header-cell> & ...

Cross-Origin Resource Sharing problem with identical URL

I encountered a CORS issue with my Angular 6 application running on port 4200 and using an API on port 3000. To address this, I implemented the following code snippet on the server side: app.use(function(req, res, next) { res.header("Access-Control-Allo ...

A guide to playing a series of audio files in succession using the Ionic Media plugin

I have been attempting to create a playlist of multiple audio files using the Ionic media plugin from here. However, I am struggling to achieve this without resorting to using a timeout function. Here is my current approach: playOne(track: AudioFile): Pr ...

The information from the data source is not getting filled in

I recently started working with Angular (Version 14.2.10) and I am trying to make a REST call to populate data in the UI. However, only the header is displayed without any data showing up. I suspect there is a minor issue that I can't seem to pinpoint ...

Tips for minimizing the number of map calls in an Angular Web App using agm-core

Our team has developed a user-friendly application using Angular with 5 pages, each featuring a Google map. The main reason for choosing Angular was to minimize the number of Map calls per user session to just 1; previously in our javascript-based app, thi ...

Display a modal dialog using HttpInterceptor

@Injectable() export class MyInterceptor implements HttpInterceptor { intercept(req : HttpRequest<any>, next : HttpHandler) : Observable<HttpEvent<any>> { //display a modal dialog to wait for user response before proceeding with t ...

Seeking guidance on transforming a thunk-based create store into a promise-based one. Any suggestions?

I am currently transitioning my app from loading data from local storage to using Firebase. Firebase always returns a promise, so I need to adapt my existing store to work with the new Firebase data. Here is the original code snippet: export const loadSta ...

The type 'ElementTypes' cannot be assigned to type 'ElementTypes.word'

After recently learning TypeScript, I encountered an error that made me think I need to write a narrower type for it or something along those lines. Here is the code snippet in question: enum ElementTypes { h1 = 'H1', word = "WORD" ...

Error: Expected an expression but found a parsing error in the eslint code

interface Address { street: string, } export const getAddress = (address: Address | null) : string => address?.street ? `${address?.street}` : '0000 Default Dr'; Why am I receiving the error message Parsing error: Expression expected ...

Moving from hosting an Angular application with "ng serve" to hosting it with Node.js involves making some adjustments to your development environment. Let's explore

After creating my first Angular2 application and hosting it with `ng serve`, I realized that I needed to add some backend functionality for server logic. Searching online, I found a helpful article on hosting an Angular 2 app on NodeJs. However, I was used ...

Issue: The element 'app-header' is unrecognized even after including 'CUSTOM_ELEMENTS_SCHEMA'

Despite the 'app-header' component being rendered in the browser, the content in the relevant "header.component.ts" or "header.component.html" files is not appearing on the screen. https://i.sstatic.net/MfKVk.png Error: 'app-header' is ...

What is the best way to implement type discrimination in TypeScript?

When using TypeScript with two interfaces combined as a union type, why doesn't it distinguish which type members can be declared? interface IFish { swim: () => void; } interface ICat { meow: () => void; } type Pet = IFish | ICat; const p ...

What is the proper way to implement `Observable.bindCallback()` in TypeScript?

Currently, I am attempting to transform a google maps direction service into an Observable pattern. Here is an example taken from https://developers.google.com/maps/documentation/javascript/examples/directions-simple: function calculateAndDisplayRoute(d ...

Implementing User Role-based Access Control in Firebase - Troubleshooting Error with switchMap

I am currently working on implementing Role-Based User Access Control With Firebase in order to grant access to a route only if the user is authenticated and has admin privileges. I am following this tutorial for guidance: My AuthService import { Injecta ...

Ways to optimize image focus on a webpage

Upon loading the page, I desire for my image to be automatically focused. Unfortunately, setting the tabindex parameter has not produced the desired outcome. This is likely due to the fact that there are multiple angular2 header components with defined t ...

Encountering a CLI error while attempting to run the 'ng serve

ng : Error encountered while trying to run ng serve. The file C:\Users\Lenovo\AppData\Roaming\npm\ng.ps1 is not digitally signed and cannot be loaded due to security reasons. To learn more about running scripts and adjusting e ...

Input the variant number TypeScript as the key value pair

I'm struggling to input an abi key "5777" in Typescript. When I receive a network ID and try to set it in the networks key, the linter displays an error. My issue is that I need to specify "networkId" and it's not always a fixed value like "5777 ...

Setting a value on an Angular form control without clearing any existing errors is a useful technique

I am encountering an issue with Angular 6 that involves manually setting formControl errors and values. My problem arises when I use .setErrors() to set the errors property on a formControl, followed by using .setValue() to set the value. Unfortunately, t ...