Angular2 - Actively selecting a checkbox in an ngFor loop with a reactive form

There is an object retrieved from a database that consists of a list of names with their corresponding IDs, as well as a flag to indicate whether they are selected or not.

Object:

let items = [{
   ID: 1,
   Name: 'Item A',
   Selected: 'Yes'
},
{
   ID: 2,
   Name: 'Item B',
   Selected: 'No'
}]

HTML:

 <div *ngFor="let item of modalData.dataItems">
   <input type="checkbox" (change)="onItemSelectionChange(item.ID, $event.target.checked)" [checked]="(item.Selected == 'Yes' ? true : false)"> {{item.Name}}<br>
 </div>

Component:

private formGroup: FormGroup;

ngOnInit() {
    this.formGroup = this.fb.group({
        selection: this.fb.array([])
    });
}


onItemSelectionChange(id: number, isChecked: boolean) {
    const selectionFormArray = <FormArray>this.formGroup.controls.selection;

    if (isChecked) {
        selectionFormArray.push(new FormControl(id));
    } else {
        let index = selectionFormArray.controls.findIndex(x => x.value == id)
        selectionFormArray.removeAt(index);
    }
}

Even though the checkboxes appear checked on the UI, when the form is submitted, the array comes back empty. What am I missing here?

onSave() {
    console.log(this.formGroup.value)
}

How can I ensure that the form maintains the initial checkbox selections and not just rely on the [checked] attribute?

Answer №1

If you need to validate your data during the OnInit event and add the validated ones to a form array, you can follow a similar approach as is done with the onChange event:

export class App {
    emails = [{email:"email1", isSelected: 'true'},{email:"email2", isSelected: 'false'},{email:"email3", isSelected: 'true'},{email:'email4', isSelected: 'false'}]
    myForm: FormGroup;

    constructor(private fb: FormBuilder) {
      this.myForm = this.fb.group({
        useremail: this.fb.array([])
      });
    }

    ngOnInit() {
      for(let item of this.emails){
        if (item.isSelected === 'true'){
          this.myForm.controls.useremail.push(new FormControl(item.email));
        }
      }
    }  

    onChange(email:string, isChecked: boolean) {
      const emailFormArray = <FormArray>this.myForm.controls.useremail;

      if(isChecked) {
        emailFormArray.push(new FormControl(email));
      } else {
        let index = emailFormArray.controls.findIndex(x => x.value == email)
        emailFormArray.removeAt(index);
      }
  }

  submitForm(event){
    console.log(this.myForm.value);
  }

}

You can view a functional Plunker demo here

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

Eliminate square brackets from URL containing an array of IDs using Request.js

My nodejs express application is sending requests with an array parameter, but it's including '[]' in the query string: For example: /foo?id=1&id=3&id=5 How can I remove the square brackets '[]' from the query string? va ...

Encountering Errors with Angular JS Following Update from Version 1.1.0 to 1.1.1

After upgrading, I noticed that the ng-repeat function is taking significantly longer to load and is attempting to display additional content boxes without serving the actual content provided by $resource. I have pinpointed the issue to the update from ve ...

How to stop a form from being cleared when a button is clicked in Angular 2

Within my form, there is a button that allows users to add an item to the object's array. <form (ngSubmit)="submit()" #myForm="myForm" class="form-horizontal" style="direction: ltr"> <div class="row"> <div class="col-md-6"> ...

In HTML, adjust column widths for multiple tables according to the widest column present in any of them

With Python, I am creating an HTML page that contains multiple tables with the same number of columns, all holding the same type of data. While the generated page is functional, I would like to improve readability by ensuring that all tables have the same ...

Modifying styles/css in Angular2 using JavaScript results in a temporary change in styles before ultimately reverting back to the original styles

Recently, I encountered an issue while trying to change styles for some elements in Angular 2 using JavaScript. Interestingly, when the view is loaded, the height is initially set to maxHeight = 100, but after a few milliseconds, it reverts back to the o ...

Dynamic x-axis movement with interactive Google Line Chart functionality

I am struggling with implementing Google charts, After reviewing Real-time changing point chart with Google Charts, I realized it is not providing the solution I need. I aim to achieve a similar result as shown in this example: Is there a method for me t ...

Issues with hydrating React local storage hook in custom implementation within NextJS

Currently facing an issue while implementing the localstorage hook in NextJS. The error message I am encountering is: Error: Hydration failed because the initial UI does not match what was rendered on the server.. Any suggestions on what might be causing ...

Issues with IE 11: SVG Map Not Triggering Mouseenter or Mouseleave Events

I've been grappling with this issue for the past couple of days and despite trying numerous solutions, nothing seems to be working. My SVG map of the US has jQuery mouseenter and mouseleave events that function properly in browsers other than IE 11 ( ...

ways to validate the calling function in jquery

One of the challenges I'm facing is identifying which function is calling a specific error function that is used in multiple places within my code. Is there a method or technique to help determine this? ...

Combining the powers of $.get and $.ready

Basically, I am facing an issue with my ajax call where sometimes it completes before the page is fully loaded. I attempted to use $( fn ) to wrap the callback function, but unfortunately, the callback does not trigger if the page is already loaded. Does a ...

Is the unit-converts npm package compatible with the website https://unpkg.com?

Having issues importing the npm package 'convert-units' using unpkg, I attempted the following method: <script src="unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="02616d6c746770762f776c6b767142302c31 ...

What is the best way to retrieve class members using component properties?

I am looking to implement a mixin for setting the header and meta data in my project. I recently discovered vue-meta, which seems to work really well for this purpose. However, I am still getting acquainted with TypeScript and class-based components. How ...

Mapping JSON data from Mongoose to Vue and Quasar: A comprehensive guide

I have set up a Mongoose backend and created some REST APIs to serve data to my Vue/Quasar frontend. The setup is pretty basic at the moment, utilizing Node/Express http for API calls without Axios or similar tools yet. I have successfully implemented simp ...

Despite passing the same dependency to other services, the dependencies in the constructor of an Angular2 Service are still undefined

To successfully integrate the "org-agents-service" into the "org-agents-component," I need to resolve some dependencies related to the required api-service. Other components and services in the hierarchy are also utilizing this api-service, which acts as a ...

Do commas at the end of JSON objects pose a risk of breaking

After diving into the proposed JavaScript features, one that caught my attention is the idea of supporting trailing commas in object literals and arrays. When it comes to parameters, trailing commas are not relevant, so let's put that aside for now. ...

Using Vue.js to set both v-model and v-bind:value on one input element

I have a React component that has a form for submitting user information. The main issue I'm facing is setting a default value in the input field. When the page loads, I want the input field to display the user's existing email address by defaul ...

`Is it possible to integrate npm libraries with typescript and ES6?`

I am looking to focus on using ES6 as the output for a node server-side app that I plan to run on the cutting-edge iojs distribution, which hopefully has support for the latest ES6 syntax. However, I'm unsure about how to integrate standard NPM libra ...

Use two queries to apply filters to entries in NextJS

Greetings to all! I am currently working on a project in NextJS that involves showcasing a portfolio of works generated from JSON data. [ { "title": "WordPress Plugin for Yandex Recommender Widget", "image" ...

Encountering issues while attempting to execute node-sass using npm

Currently, I'm attempting to execute node-sass using npm. Displayed below is my package.json: { "name": "my-project", "version": "1.0.0", "description": "Website", "main": "index.js", "scripts": { "sass": "node-sass -w scss/ -o dist ...

Passing a type as an argument in Typescript

How can I pass a type as a parameter in Typescript? type myType = {} const passingType = (t: Type) => { const x : t = {} } passingType(myType); I keep receiving TypeScript errors. 't' is referencing a value, but it is being used as a t ...