Angular2 - Working with form elements within form elements

I'm currently working on a project that involves dynamically adding and removing form elements. You can check out an example I’m following at this link.

In the HTML file, I encountered a warning message regarding the 'filters' identifier not being defined within the code even though it functions correctly. The selects in the form are interlinked, meaning selecting one level will automatically populate all level selects.

<table class="example-full-width" cellspacing="0" formArrayname="filters" *ngFor="let filters of eventForm.controls.filters.controls; let i=index">
  <span>Address {{i + 1}}</span>
   <span *ngIf="eventForm.controls.filters.controls.length > 1" (click)="removeFilters(i)">x</span>
  <tr>
    <td>
      <md-select [(ngModel)]="filterUserOcc" [ngModelOptions]="{standalone: true}" placeholder="Occupation" (ngModelChange)="filterUserOccupation()">
        <md-option [value]="null">Occupation</md-option>
        <md-option *ngFor="let occupation of occupations | async" [value]="occupation.occupation">
          {{ occupation.occupation }}
        </md-option>
      </md-select>
    </td>
  </tr>
  <tr>
    <td>
      <md-select [(ngModel)]="filterUserLvl" [ngModelOptions]="{standalone: true}" placeholder="Level" (ngModelChange)="filterUserLevel()">
        <md-option [value]="null">Level</md-option>
        <md-option *ngFor="let level of levels | async" [value]="level.level">
          {{ level.level }}
        </md-option>
      </md-select>
    </td>
  </tr>
</table>

app.module.ts

...
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
...


imports: [
...
    ReactiveFormsModule,
 ...
  ],

component.ts

...
import { FormGroup, FormControl, FormArray, FormBuilder, Validators } from '@angular/forms';
...

export class NewEventComponent implements OnInit {

  eventForm: FormGroup;
...


  constructor(
...
    private formBuilder: FormBuilder,
...
  ) {
...
  }

ngOnInit() {
    this.eventForm = this.formBuilder.group({
...
      filters: this.formBuilder.array([
        this.initFilters()
      ])
    });

  }

initFilters() {
    return this.formBuilder.group({
      level: ['', Validators.required],
      occupation: ['']
    });
  }

  addFilters() {
    const control = <FormArray>this.eventForm.controls['filters'];
    control.push(this.initFilters());
  }

  removeFilters(i: number) {
    const control = <FormArray>this.eventForm.controls['filters'];
    control.removeAt(i);
  }

Answer №1

The reason behind this issue is the use of two-way-binding with a single variable, such as in the case of level, like [(ngModel)]="filterUserLvl". This results in all the level's having the same value within the form.

It's not recommended to employ two-way binding when working with reactive forms; it's better to utilize the form controls instead of ngModel.

I also observed that you forgot to include formGroupName for each form group in your array, so I made some adjustments to...

<div formArrayName="filters">
  <table *ngFor="let filters of eventForm.controls.filters.controls; let i=index" 
       [formGroupName]="i">
....

Just remove the ngModel and ngModelChange from your template and everything should work smoothly!

If you require a change event to be triggered when altering the select option, you can pass the actual form control.

Check out the DEMO

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

What is the best way to prevent excessive rerenders when verifying if database information has been successfully retrieved?

Hey there, I'm encountering an issue where the if statement check in my code is causing a "too many rerenders" problem. I'm trying to create a delay between pulling data from the database and calculating the BMI. Any suggestions on how to resolve ...

The error message states: "Dygraph is not defined."

Currently, I am utilizing express.js in my application to render dygraph charts on the client side. You can take a look at my index.jade file here. Upon visiting my browser, an error pops up in the console: Uncaught ReferenceError: Dygraph is not defined. ...

Exploring Angular Ag-Grid: Enhancing Row Expansion with a Simple Click

How can I increase the height of a particular row in Angular Ag Grid when clicked? I've edited the code in Stackbiz. Click here to see the edited data This is an example running from ag grid Tutorial Grid Tutorial Example ...

Using Three.js with Webpack 5 and FBXLoader inline integration

I am currently working with Webpack 5 and attempting to provide a direct file path to my FBXLoader using the latest Webpack asset modules: const loader = new FBXLoader() loader.load('../assets/models/myModel.fbx', (object) => { ... }) // encou ...

cutting tags with priority levels

I'm facing an issue where the vertical label "PINK" is centered perfectly in a section, but when I scroll down to the next section, it gets covered by a section with a higher z-index. div.back1 { background-color: #FF00FF; position: relativ ...

Utilizing Angular Material's matMenu for custom context menus

I've been exploring how to implement a matMenu as a context menu that appears when someone right-clicks on one of my elements. Here is the menu structure: <mat-menu #contextMenu="matMenu"> <button mat-menu-item> <mat ...

Choosing the default checkbox option as selected in a ReactJS application

Is there a way to preselect checkboxes in ReactJS based on certain output data? For example, I have the following output: {permission:{group:["can_view"],"topGroup":["can_update"]}} . After sending this data to the database and receiving back the edited ...

End the rendering process in Three.js

When loading a large obj file on computers that do not support WebGL, the process can become too slow. To address this issue, I am looking to upload a lighter object before and after the complete object loads. However, I need a way to pause the rendering p ...

How can I stop jQuery mobile from updating the document title?

It appears that jQuery mobile automatically uses the text content of data-role="header" to set the document.title. For example: <div data-position="fixed" data-role="header"> <h1>This text</h1> </div> To work around this, I ha ...

Why am I receiving a "Cannot read property 'style' of undefined" error when using the Nanoscroller?

This is the code snippet I've been working on: <ul id="selectProfileOptions_IC" class="dropdownToggle_cont" ></ul> Under this ul element, I have listed some names. To enable scrolling functionality, I employed nanascroller in my project ...

Having trouble executing a jQuery function within AJAX-generated code

I may not be very experienced in JavaScript programming, but I am learning and trying my best to improve. Please excuse any errors I make along the way. Currently, I am attempting to use Ajax (not jQuery ajax) to save customer details, which then returns ...

Warning: The file or directory 'C:UsersNuwanstpackage.json' does not exist

Can someone help me with installing socket.io in my project located in the 3.chat folder? I'm encountering some warnings when running the command and it's not creating a node_modules directory. Any suggestions on how to resolve this? C:\Use ...

Clearing Time Field Input in Safari

Recently, I've been utilizing the following HTML input element: <input type="time"> While testing it in both Chrome and Safari, I noticed that the clear field (cross button) is absent when using Safari. How can I make the cross button appear i ...

Tips for resolving the npm glob-parent dilemma

Vulnerability in glob-parent <5.1.2 Detected Severity Level: moderate Description: Regular expression denial of service - More information at https://npmjs.com/advisories/1751 Resolution: fix available through `npm audit fix` Affected Package: node_modu ...

Organizing Data to Create a D3 Tree Layout from a CSV

My CSV file has the following structure source, target, name, value1 , percentange A1 A1 T1 200 3% A1 A2 T2 340 4% A1 A3 T3 400 2% I want to create a tree diagram similar to this D3 Pedigr ...

Navigating my smart contract through a web browser

After successfully deploying my contract on ropsten network, I attempted to interact with it through a web browser. However, I encountered an error message stating that it is not a function. Interestingly, when I tried interacting with the contract on Node ...

jQuery must provide the complete object rather than just the data within it

What is the best way to retrieve the entire <div class="loan_officer_apply_now_link"><a href="">APPLY NOW!</a></div> At present, only the "a" element content is being returned <a href="">APPLY NOW!</a> Test Code $( ...

What could be the reason behind Cors preventing my API request?

Currently, I am in the process of developing a project that requires me to access an API that I have created. const endpoint = 'localhost:3000/api/v1/'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'appl ...

What is the best way to convert a state variable into a string in this scenario?

I have encountered an issue while using the NPM package react-date-countdown-timer. The countdown timer in this package requires a specific format for implementation: <DateCountdown dateTo='January 01, 2023 00:00:00 GMT+03:00' callback={()=> ...

What could be the reason behind the sudden inability of JavaScript prompt newlines to copy-paste into windows applications?

This function grabs the text from a single row in a table and shows it, alongside the text from the header row, in a prompt for users to copy and paste. It was functioning properly earlier, but now the newlines are not being included when pasting from the ...