In Angular 6, the FormArray function will output an empty array

I am looking to create a dynamic form using form arrays. When I click on (click)="AddInfoName()", it should add a new form.

Here is the HTML code I am using:

<form class="form-line" [formGroup]="addinfoForm" (ngSubmit)="AddRole()">
                <div formArrayName="infoName">
                    <div class="description" *ngFor="let name of InfoFormGroup.controls; let NameIndex=index" [formGroupName]="NameIndex">
                    <div [formGroupName]="i" class="row">
                        <label class="form-line">  Name   :   </label>
                        <input style="margin-right: 50px;" class="form-line" pInputText id="pFaName" formControlName="infoName">
                        <app-filederrors [form]="addinfoForm" 
                            field="getInfoFormGroup(NameIndex)"
                            nicename="Name">
                        </app-filederrors>
                    </div>
                    </div>
            </div>
        </form>

And in my TypeScript file, here is the corresponding code:

 addinfoForm:FormGroup;
  infoNameList:FormArray;
  infoModel:Productdetail;

  constructor(private fb:FormBuilder,private router:Router,private tokenService:TokenstoreService) { }

  ngOnInit() {
    this.infoNameList = this.fb.array([]);
    this.InfoForm();
  }

  /**
   * AddInfoForm
   */
  public InfoForm() {
    this.addinfoForm=this.fb.group({
      infoName:this.fb.array([this.CreateInfoName()])
    })
    this.infoNameList=this.addinfoForm.get('infoName') as FormArray;
  }

  get InfoFormGroup(){
    return this.addinfoForm.get('infoName') as FormArray;
  }

  public CreateInfoName():FormGroup{
    return this.fb.group({
      infoName:['',Validators.compose([Validators.required])]
    });
  }

  public AddInfoName(){
    this.infoNameList.push(this.CreateInfoName());
    console.log('sdkjfghjkdfgh')
  }

  public RemoveInfoName(index:number){
    this.infoNameList.removeAt(index);
  }

  getInfoFormGroup(index:number):FormGroup{
    const formGroup=this.infoNameList.controls[index] as FormGroup;
    return formGroup;
  }

  AddInfo(){
    console.log('in form ==>',this.addinfoForm.value)
  }

However, I am encountering two problems with this code:

1 - When creating a new form, I receive the following error:

Error: Cannot find control with path: 'infoName -> 0 -> '

2 - The infoName array appears to be empty. Even though I create 5 forms, adding data shows an empty array like this:

`infoName: Array(5)
0: {infoName: ""}
1: {infoName: ""}
2: {infoName: ""}
3: {infoName: ""}
4: {infoName: ""}`

What could be causing these issues and how can I resolve them?

Answer №1

Consider eliminating the unnecessary use of [formGroupName]

A better approach would be as follows

<form class="form-line" [formGroup]="addinfoForm" (ngSubmit)="AddRole()">
    <div formArrayName="infoName">
        <div class="description" *ngFor="let name of InfoFormGroup.controls; let NameIndex=index" [formGroupName]="NameIndex">
            <div class="row">
                <label class="form-line"> نام : </label>
                <input style="margin-right: 50px;" class="form-line" pInputText id="pFaName" formControlName="infoName">
                <app-filederrors [form]="addinfoForm" field="getInfoFormGroup(NameIndex)" nicename="نام">
                </app-filederrors>
            </div>
        </div>
    </div>
</form>

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

Combining Files with Gulp.js and Handling File Names

I need a solution that will add the file name as a comment to each file in the stream. This means creating a comment line with the file path in the final destination file. The current functionality is as follows: pseudocode: concat(file1, file2) # outpu ...

Combining audio and video streams in Node.js

I'm currently developing a YouTube video downloader using the ytdl-core library. However, I've encountered an issue where it cannot fetch high quality videos with audio because they are stored in separate files on YouTube. My goal is to download ...

Check for Compatibility with Fullscreen API on Device or Browser

Is there a way to determine if a web browser supports the FullScreen API using JavaScript? As far as I know, the most recent version of Safari enables it on iPads but not on iPhones. I'm curious about how to check if the device has support for the F ...

What is the best method for comparing two elements effectively in JavaScript?

Check out this code snippet that ensures txtKeyword input is focused when a key is pressed by the user. var txtKeyword = document.getElementById("txtKeyword"); ... document.addEventListener("keypress", function(event) { if(event.src ...

Display a loading animation while the collapsible block is expanding in jQuery Mobile

I am experiencing an issue with displaying a loading icon when a collapsible block is opening. Within the collapsible block, there is a dynamically populated listview generated through ajax/php. This list could potentially contain up to 500 elements, so I ...

Positioning of the dropdown in Material UI Autocomplete

Can the Material UI Autocomplete be customized easily to position the Popper dropdown relative to the text cursor, similar to the VS Code Intellisense dropdown? The input field is a multiline Textfield component. The code snippet below demonstrates: impor ...

Utilizing JQuery for a smooth animation effect with the slide down feature

I have a question about my top navigation bar animation. While scrolling down, it seems to be working fine but the animation comes with a fade effect. I would like to achieve a slide-down effect for the background instead. Since scrolling doesn't trig ...

Occasionally, the map may take a moment to fully load

Update: Resolving the issue involved directly calling these two methods on the map object: leafletData.getMap().then(function(map) { map.invalidateSize(); map._onResize(); }); Encountering a minor yet bothersome problem with the Leaflet directive ...

Exploring the power of nesting methods within *ngIf

project[col.field][selectedUserRole.value].join(',').length When attempting to use the code above within *ngIf or inside curly braces {{}}, an error occurs: ERROR TypeError: Cannot read property 'join' of undefined This error indic ...

Using jQuery to create a function that triggers when the value of a text input is altered

I am currently working on creating a function that will be triggered when the value of a text input changes. The function works fine if I manually change the value, but it does not work if the value is changed automatically by an event on another element. ...

Using Vue.js to display and render HTML content retrieved from an API call

Currently, I am working on displaying data received from an API call using Vue. A part of the data is being returned in escaped HTML format like this: body: "&lt;ul&gt; ↵ &lt;li&gt;This is &lt;strong&gt;Test Text.&lt;/stron ...

SyntaxError: Unexpected symbol

I have an issue with the following code: let op = data.map(({usp-custom-90})=> usp-custom-90 ) When I run it, I encounter the following error: Uncaught SyntaxError: Unexpected token - I attempted to fix it by replacing the dash with –, but t ...

React timer slide show malfunctioning

While I have some experience with React, I'm struggling with a seemingly simple problem that I just can't figure out. My goal is to cycle through an array of images and display the image at the current index. The console logs show the correct in ...

How to use jQuery to locate and update the final parameter of a URL

Hello everyone, I've already done some research but couldn't find a solution that fits my needs. Can anyone assist me with this? I currently have a URL "/view/album/4/photo/1" and I am looking to remove the final parameter and replace it with so ...

Converting JSON Data to HTML Display

I'm currently utilizing the Google Feeds API to showcase the most recent posts from my Facebook account. The statuses are being fetched from an XML file on fbrss.com, and the code below is functioning correctly: <script type="text/javascript" ...

Tips for deactivating a single edit button

Is there a way to make it so that when I click on a checkbox, only that specific todo's edit button is disabled? Currently, clicking on a checkbox disables all edit buttons in the todo list. Any suggestions? class App extends Component { state ...

Error encountered while executing mysql command

My database has a table named beneficiaries with the following columns: custid varchar accno varchar primarykey name varchar There is currently one record in the table with these values: 101 12345 john Now I want to insert a record for another custid b ...

Set the background color of the Material UI Drawer component

Need some advice on changing the background color of Material UI's Drawer. I've attempted the following approach, but it's not producing the desired result. <Drawer style={customStyle} open={this.state.menuOpened} docked={false} ...

When calling an array's values from another function, the values seem to mysteriously vanish in Javascript

I am currently working on creating a form using JavaScript that needs to perform two key functions: 1) Dynamically adding elements to a list 2) Identifying a specific element (e.g. the one with the highest value) upon button click To visualize what I ha ...

Is there a way to convert a Blob object to a JSON object in Javascript?

let dataFile = new Blob([response.data], {type: 'application/json'}); Within the response.data is a JSON file. My goal is to extract the contents of this file and set them as a JSON string to a variable in JavaScript. I've experimented wit ...