How to retrieve values from multiple checkboxes in Angular?

After retrieving data from getListOfCurrentSubtenants and displaying it as shown in the screenshot, users have the ability to select items by clicking on checkboxes. How can we capture all the selected data into a single object?

For example, if a user checks 5 boxes, the result should be an array of objects containing all the selected items.

Sample Object:

[
    {
        "subtenantName": "Urgent Care MSO, LLC",
        "currentLeaseExpiration": "04/30/2023"
    },
    {
        "subtenantName": "Laboratory Corporation of America",
        "currentLeaseExpiration": "10/10/2028"
    }
]

HTML Code:

<div *ngIf="currentSubtenants.length > 0" class="deal-form-header-labels" style="padding-top: 5px;">Current Subtenants</div>
          <div *ngFor="let subtenant of currentSubtenants; let i = index;" class="subtenant-form-btn-group">
            <div class="deal-form-btn-group-radio" fxLayout="row" fxLayoutAlign="space-between center" >
              <div class="pharmacy-checkbox">
                <mat-checkbox
                 color="primary"
                 [(ngModel)]="dealDispositionFormFields.currentSubtenants"
                 (change)="changeCurrentSubtenants($event,subtenant)"
                 style="margin-left:10px;">
                 <div class="deal-text-label">
                   {{subtenant.subtenantName}}
                </div>
                </mat-checkbox>  
                </div>
            </div>
            <div >
              <div class="flex-column">
                <mat-label>Current Lease Expiration</mat-label>
                <div class="property-assignments-email secondary-text">{{subtenant.currentLeaseExpiration}}</div>
              </div>
            </div>
          </div>
        </div>

JavaScript Function:

changeCurrentSubtenants(e:any,rowData:any){    
    if(e.checked){
      console.log("rowData" , rowData)
    }
}

    getListOfCurrentSubtenants() {
          this.partnerRoleIsInProgress = true;
           this._dealService.getCurrentSubtenants(this.transactionData.propertyId)
            .pipe(
              finalize(() => this.partnerRoleIsInProgress = false),
            ).subscribe({
              next: (res) => {
                if (res.isSuccess) {
                  this.currentSubtenants = res.data;
                  console.log("res" , this.currentSubtenants)
                }
              },
              error: err => this._notificationService.showError(err),
              complete: noop
            });
        }

https://i.sstatic.net/9grog.png

Answer №1

To enhance your code without extensive refactoring, consider utilizing an array to add and remove items.

interface Information {
  subtenantName: string;
  currentLeaseExpiration: string;
}


collection: Information[] = [];
updateSubtenants(e: any, dataRow: Information) {
  if (e.checked) {
    this.collection.push(dataRow);
  } else {
    this.collection = this.collection.filter(item => item.subtenantName === dataRow.subtenantName);
  }
}

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 process for launching the application directly to a specific component?

Hello everyone, I'm currently developing my app using Angular and have just started implementing routing. My question is, how can I ensure that the HomeComponent loads automatically when the site is opened? ...

Custom filtering in jqGrid with an integrated filtering toolbar

Hey there! I'm currently using the latest version of jqGrid and I was curious if it's possible to implement local filtering with custom rules. In the past, I had to manually add this feature because the version I was using didn't support it. ...

`Node.js troubleshooting: Dealing with file path problems`

I am currently in the process of deploying a node.js based application to IBM's Bluemix and have made some modifications to one of their provided samples. I have included an additional javascript file that initiates an ajax call to PHP, but unfortunat ...

Even though my form allows submission of invalid data, my validation process remains effective and accurate

Here is the code I have written: <!doctype html> <html lang="en"> <head> <title>Testing form input</title> <style type="text/css></style> <script type="text/javascript" src="validation.js"></script> &l ...

Is there a way to link a particular model table with a designated user table?

Hey everyone, I'm new to stack overflow and this is my first question. I hope it's clear enough for you all to understand. I'm currently working on a budget API using Node.js, Sequelize, Express, and PostgreSQL. The API allows users to add/ ...

The proxy is unable to access the method within the subclass

Issues are arising as I attempt to utilize a Proxy. The structure of my class is as follows: export class Builder { public doSomething(...args: (string | number | Raw | Object)[]): this { // Do stuff return this } } export class M ...

Is it necessary for vertex labels to be distinct within a graph?

I am currently developing a browser-based application that allows users to create graphs, manipulate them, and run algorithms on them. At the moment, each vertex is represented by a unique positive integer. However, I am considering implementing labeled ve ...

The items in the Bootstrap dropdown are not displaying

I am currently working on a project using Angular 12, and I encountered an issue with my Bootstrap dropdown menu not displaying any items. Below is the HTML code snippet causing the problem: <nav class="navbar navbar-expand navbar-dark"> ...

Exploring ngAfterViewInit and ngAfterContentChecked

This question pertains to a common issue raised on StackOverflow multiple times. In essence, when you encounter a scenario such as: @Component({ selector: 'my-app', template: `<div>I'm {{message}} </div>`, }) export class A ...

The Cypress executable cannot be located in the directory: /root/.cache/Cypress/3.8.3/Cypress/Cypress

Encountered an issue with the error message 'Cypress executable not found at: /root/.cache/Cypress/3.8.3/Cypress/Cypress' when running the cypress command 'npx cypress run -P projects/demoProject-cypress' on docker in the cloud environm ...

Encountering an issue while trying to set up a fresh react application

Issue encountered when trying to start a new React project ...

Using AngularJS and JavaScript, set the Submit button to be enabled only when the email input is valid and a value is selected in

I'm trying to create a form that includes an email input field and a drop-down list sourced from a database array. Initially, the submit button is disabled when the form loads. My goal is to figure out how to activate the submit button only when the ...

Determine the total hours and minutes elapsed between two specific dates and times

Looking for some assistance here. I have a form where users need to input a start time and end time of an incident. After entering this information, they would manually calculate the duration between the two date times. I am attempting to streamline this p ...

Adjust the object size to match the Viewport dimensions

I've been developing a VR world where the camera can be turned and tilted in the center but not moved around freely. Within this virtual reality environment, you have the ability to attach a video to the background. Users can either play it by clicki ...

Obtaining the selected date value from a Vue.js datepicker

How can I calculate the difference in days between two selected dates in Vue.js before the form is submitted? I want to provide a price based on this calculation. I am using a Persian date picker, which you can find here: https://github.com/talkhabi/vue- ...

Can AngularJS be integrated with prototype methods and variables?

When working with AngularJS, the majority of logic is typically based on the $scope: function Ctrl($scope) { $scope.name = "Freewind"; $scope.hello = function() { alert($scope.name); } $scope.method1 = function() {} $scope.metho ...

React.js encountered an error: Objects cannot be used as a React child (found: object containing keys {type, data})

My current project involves displaying MySQL data in a table using Node.js and React.js. However, I keep encountering the following error: Error: Objects are not valid as a React child (found: object with keys {type, data}). If you meant to render a colle ...

Issues with the JavaScript, HTML, and CSS Counter Implementation

Is there anyone who can assist me in making this code (available at https://jsfiddle.net/hmatrix/v3jncqac/) function properly? Purpose: My goal is to develop a counter that increments by specified values. My HTML: <body onload="incrementCount(10)"> ...

The bundle injected by Webpack-dev-server into the HTML page fails to display any rendered content

Whenever I execute webpack-dev-server (Command: "webpack-dev-server --mode development --open --progress --hot"), the bundle gets injected into the html page, but nothing actually appears on the screen. This is how my Webpack.config.js file looks like: v ...

What is the best way to organize code into separate files while utilizing a module that needs to be included in every file?

In this particular scenario, I am utilizing a headless browser with Puppeteer Chrome and MongoDB. Take a look at the following code snippet: var browser = await puppeteer.launch() var page = await browser.newPage() var db = await MongoClient.connect(" ...