Adding the checked value to an array in Angular2 whenever an item is checked

One of my components is set up to receive an object containing employee records and display them in a table. Each record includes a checkbox that allows users to "select" the employee for inclusion in the next process.

<tr *ngFor="let i of importResults" >
 <td>
  <input type="checkbox"
         value="{{ i.QID }}"
         attr.data-employeename="{{ i.PreferredName }} {{ i.LastName }}"
         [checked]="isSelected" />
  </td>
  <td>{{ i.PreferredName }} {{ i.LastName }}</td>
</tr>

To manage this selection, I have created an array called selectedEmployees = [];. The idea is that when a user clicks on a checkbox, its value should be added to the array. Similarly, if the checkbox is unchecked, the value should be removed from the array.

I initially tried using ngModel for two-way binding, but encountered issues due to the lack of an initial checked value in the object. Is there a better approach to achieving this functionality?

While exploring solutions, I came across a related question on Stack Overflow, but encountered an error in Typescript regarding the use of .entries. Could this be due to compatibility issues with older versions of Angular?

Answer №1

If you want to implement a feature where clicking on a checkbox triggers an action to add or remove an item, you can achieve this by adding a `click` event to the checkbox element and passing it to a function for handling.

Here is an example of how you can set up your HTML:

<div *ngFor="let i of importResults" >
 <div>
  <input type="checkbox"
         value="{{ i.QID }}"
         (click)="change(i)"/>
   <span>{{ i.PreferredName }} {{ i.LastName }}</span>
  </div>
</div>

<p> Selected Employee: {{selectedEmployees | json}} </p>

In your component.ts file, you can have the following code snippet:

export class SelectFormExample {
  selectedEmployees = [];

  showSiblingComp = false;

  importResults = [
    {QID: "1", PreferredName: 'Steak', LastName: "Pizza"},
    {QID: "2", PreferredName: 'Cheese', LastName: "Burger"},
    {QID: "3", PreferredName: 'Chicken', LastName: "Panini"}
  ];

  constructor(private service: SharedService){

  }

  change(obj){

    let updateItem = this.selectedEmployees.find(this.findIndexToUpdate, obj.QID));

    let index = this.selectedEmployees.indexOf(updateItem);

    console.log(index);

    if(index > -1){
      this.selectedEmployees.splice(index, 1);
    }
    else{
      this.selectedEmployees.push(obj);
    }

    this.service.setList(this.selectedEmployees);

  }

  findIndexToUpdate(obj) { 
        return obj.QID === this;
  }
}

You can view a demo of this implementation here.

This demo also includes sharing the `selectedEmployees` data with a sibling component using a shared service.

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

Issues with the radio-inline class in Angular and Bootstrap causing functionality errors

Trying to align my radio buttons on one line using the radio-inline class from bootstrap. Here's my code: <label>Fattura a carico di </label> <label class="radio-inline control-label"><input type="radio" value="banca" n ...

Confirm the identity of a user by checking their email against the records stored in a MySQL database

I am currently working on creating a user verification system using email that is stored in a mySql database and utilizing express JS. The user is required to input their email before filling out any other forms. If the email is not found in the email tabl ...

Subscriber fails to receive updates from Behavior subject after calling .next(value)

I am facing an issue where a Behavior Subject does not update a subscriber upon the .next(value) call. Being new to typescript, I believe I might be overlooking something small. The implementation seems correct based on what I have researched. Although t ...

Radio buttons with multiple levels

Looking to implement a unique two-level radio button feature for a specific option only. Currently, I have written a logic that will display additional radio buttons under the 'Spring' option. However, the issue is that when it's selected, t ...

Getting a precise element from an array in JSON using Angular 5

I've been struggling to fetch a specific value ("isRight") from a JSON object. I have tried multiple solutions found on stackoverflow and even compared my code with one of them, but I keep getting the value as undefined without any errors. { ...

What is the procedure for including a attribute in all sub-objects within a nested object using Typescript?

I need to create a function called addId that takes an object as input and returns the same object with an added property _id: string in every sub-object. Let's consider the input object constructed from the following class. class A { a: number b ...

Tips for creating an interface that dynamically expands according to a component's properties

Imagine having a custom Button component along with its corresponding ButtonProps interface. interface ButtonProps { component?: ComponentType; label: ReactNode; onClick?: (evt: React.MouseEvent<HTMLButtonElement>) => void; } Is there a wa ...

Can ES6 class getters, setters, and private properties be utilized in TypeScript with an interface?

I'm currently using TypeScript and trying to figure out how to implement an interface in a class that utilizes ES6 getters and setters. Is it even possible? When I use the code below, errors are highlighted in the class. For instance: (property) S ...

Is there a way to obtain a unique response in TestCafe RequestMock?

With Testcafe, I have the capability to simulate the response of a request successfully. I am interested in setting up a caching system for all GET/Ajax requests. The current setup functions properly when the URL is already cached, but it fails to prov ...

Creating an observable in rxjs6 Angular6 that automatically unsubscribes itself

I'm attempting to create an observable that will update the database status to 'away' when the mouse hovers over the document. Then, if the mouse becomes active again, it should update the status back to 'online'. Here is my curre ...

Managing background tasks with Node.js in real-time

I am currently faced with the challenge of managing background events. When a user is temporarily banned, we save the ban expiration in our database to ensure they are unbanned at the right time. However, my current code checks every ban every 10 seconds ...

Navigating the "this" scope within a callback function while in strict mode

Having some trouble with error TS2683 when using webix(5.4.0) + typescript(3.1.1) in strict mode. ($$('DATE') as webix.ui.datepicker).attachEvent('onChange', function() { let val:any = this.getValue() // or let val = ... without ...

The search for d.ts declaration files in the project by 'typeRoots' fails

// Within tsconfig.json under "compilerOptions" "typeRoots": ["./@types", "./node_modules/@types"], // Define custom types for Express Request in {projectRoot}/@types/express/index.d.ts declare global { namespace Express { interface Request { ...

Adjusting the ng-turnstile Dimensions

Looking for a way to adjust the width of CloudFlare Turnstile to match its parent container's layout without causing any issues with the Iframe. Is there a more efficient method to achieve this? The current solution I have seems to be messy: import { ...

"Troubleshooting: Issues arise with Kendo UI Angular file upload component when dealing with

Currently, I have integrated the Kendo Angular File Upload component into my Angular 7 application. The backend of this application is built using ASP.NET Core 2.1 and hosts a MVC API through Kestrel. While the file uploads for smaller files are successful ...

Using async await with Angular's http get

In my service component, I have the following code snippet that retrieves data from an API: async getIngredientsByProductSubCategory(productSubCategoryId: number) { const url = '/my-url'; let dataToReturn: any; await this.http.get(ur ...

Include new item to the Observable array in TypeScript

I've created an Angular 2 component that utilizes a service to fetch data from a REST API. import { OnInit, Component } from '@angular/core'; import { Hero } from './hero'; import { HeroService } from './hero.service2'; ...

In Typescript, an interface is defined where the "id" property is required to be a number, while all other properties must be of

I am in need of creating an interface to represent data received from the server, where the id is a number and all other properties are strings. This is what I attempted: interface AnyChartsData { id: number; [key: string]: string; } However, I enco ...

Unable to retrieve the regex value with an alternate label

Here is a RegExp expression that I am currently using: const regex = new RegExp('<(.*)>' + text + '<(.*)>'); renderer.setProperty(node, 'innerHTML', node.innerHTML.replace(regex, '<$1>' + replaceTe ...

"Problems with auto-import feature in VSCode for a new and tidy Angular project

As I work on my pristine Angular 10 project using Typescript 3.9.7, I've encountered an issue with some of the auto imports and suggestions not functioning correctly. For instance, when trying to import FormsModule from @angular/forms by typing FormsM ...