Retrieve the product IDs by selecting the checkboxes, then compile a fresh array consisting of the identified IDs

I am currently delving into the realm of typescript/angular2+ as a fledgling student, and I have taken on the task of creating a website to put my newfound knowledge to the test.

The view is up and running, but I'm facing some roadblocks as I work on developing the update page.

On this update page, I have 2 select dropdowns and a table with checkboxes that can be selected.

For the selects, I'm utilizing the (valueChanged) event to capture the selected id.

Within the table, I'm using [(ngModel)] to handle the checkbox selections.

Essentially, the process I'm trying to achieve involves:

- Acquiring the id from the first select dropdown

- Selecting one or more products from the table using checkboxes

- Retrieving the id from the second select dropdown

Upon selecting checkboxes, I receive an array with product information. However, I only need the ids from this array to be sent to the backend. The challenge is that I require these ids to be in an array format, as per the configuration of my backend, which accepts data in the form of a list using a Data Transfer Object (DTO).

Here's an example of the array structure:

[{"id": 2225, "name": "Joy Price", "isSelected": true}, {"id": 2226, "name": "Ronnie Jordan", "isSelected": true}]

To sum up, I need to extract the ids from the checkedCategoryList and assemble a separate array to submit to the idsProducts field in the model.

I'm currently stuck on how to best approach this issue and would appreciate any guidance on how to proceed.

update.component.html


// HTML code snippet for the update component

update.component.ts


// Typescript code snippet for the update component

update.model.ts


// Typescript code snippet for the update model component

update.service.ts


// Typescript code snippet for the update service component

Answer №1

latest update as of 9-9-2021

Here is a new method using the Set data structure:

Example:-

Component TypeScript File

 uniqueIdsUsingSet: Set<number> = new Set();

  prods = [
    { id: 2225, name: 'Joy Price' },
    { id: 2226, name: 'Jordan Ronnie ' },
    { id: 2227, name: 'Price Jordan' },
    { id: 2228, name: 'Ronnie Joy' },
  ];

 uniqueArryUsingSet(item: HTMLInputElement): void {
  if(item.checked) {
   this.uniqueIdsUsingSet.add(+item.id);
  } else {
   this.uniqueIdsUsingSet.delete(+item.id);
  }
 }

Component HTML File

<ng-container *ngFor="let prod of prods">
  <div>
    <label [for]="prod.id">
      {{prod?.name}}
    </label>
    <input
      [id]="prod.id"
      type="checkbox"
      [value]="prod.id"
      #item
     (change)="uniqueArryUsingSet(item)"
    />
  </div>
</ng-container>

Old Method:

Component TypeScript File

  uniqueIds: any[] = [];

  prods = [
    { id: 2225, name: 'Joy Price' },
    { id: 2226, name: 'Jordan Ronnie ' },
    { id: 2227, name: 'Price Jordan' },
    { id: 2228, name: 'Ronnie Joy' },
  ];

  makeUniqueArrayItems(item: HTMLInputElement): void {
    const itemIndex = this.uniqueIds.indexOf(item.id);
    !item.checked
      ? this.uniqueIds.splice(itemIndex, 1)
      : this.uniqueIds.push(item.id);

    this.uniqueIds = [...new Set(this.uniqueIds)];
  }

Component HTML File

<ng-container *ngFor="let prod of prods">
  <div>
    <label [for]="prod.id">
      {{prod?.name}}
    </label>
    <input
      [id]="prod.id"
      type="checkbox"
      [value]="prod.id"
      #c
      (change)="makeUniqueArrayItems(c)"
    />
  </div>
</ng-container>


<div *ngIf="uniqueIds?.length">
  <h3>
    Selected Values
  </h3>
{{uniqueIds}}
</div>

Try out the example on StackBlitz 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

The Fixed Navbar is causing sections to be slightly off from their intended positions

Utilizing a bootstrap navigation menu on my website with a fixed position. When clicking a menu item, it takes me to the designated section but slightly above the desired position. How can I ensure that it goes to the exact position upon clicking the men ...

Utilizing an API to dynamically augment a JSON object with user input in Angular

Hello, I am working on adding an input value to an object property. The scenario is that a customer wants to add an item to their shopping cart, but before adding the item, they need to choose the size. I have the form set up with validation and can retri ...

Angular: Enhancing URL links

Recently, I discovered a function in my code that allows me to cycle through different pictures and change the URL accordingly. The initial URL is obtained using angular routes, where the "domain" parameter consists of the domain.id and the domain.category ...

Mastering the Art of Scrolling

Can someone please tell me the name of this specific scrolling technique? I am interested in using something similar for my project. Check out this example site ...

What steps can I take to troubleshoot why a pop-up window will appear in web Outlook but not in the 2016 version

While my dialog opens correctly in the Office web app, it only displays a loading indicator and shows "working on your request" in Office 2016. I've attempted to add a task pane, which successfully works and allows me to accept the HTTPS certificate o ...

Converting a JavaScript string into an array or dictionary

Is there a way to transform the following string: "{u'value': {u'username': u'testeuser', u'status': 1, u'firstName': u'a', u'lastName': u'a', u'gender': u'a&a ...

A versatile JavaScript function built to efficiently validate numerous forms across a webpage

Sorry for the simple query, but I'm still learning JavaScript. I have a script that checks if a text field is empty to validate user inputs. If it's not empty, a confirmation window pops up before submitting the form and uploading the information ...

Is there a method for executing ng-serve alongside expressjs?

I am currently following an Angular6/Express tutorial. In the tutorial, they utilize the following scripts: "scripts": { "ng": "ng", "start": "ng build && node ./bin/www", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e ...

Is Joomla equipped with shortcodes akin to those found in Wordpress?

One of the great features of WordPress is the ability to use shortcodes to insert information into HTML without the need for programming knowledge in PHP or JavaScript. This simplifies tasks and increases safety. For example (this is just a hypothetical s ...

When working with an outdated package, you may encounter a situation where babelHelpers is not

My current focus is on a vuetify v1.5 project. Unfortunately, one of the dependency packages (d3-flextree) is causing an issue with the 'babelHelpers is not defined' error. The solution I came across suggests using transform-runtime instead of th ...

Utilizing TypeScript's Exclude feature with a generic type

An update to dependencies in my TypeScript-based Nodejs project has led to compilation errors when working with a generic class that manages mongoose models. The root cause appears to be related to how TypeScript handles generic types. To illustrate the i ...

Preventing Columns in SlickGrid from Being Reordered

Is there a way to prevent specific columns in SlickGrid from being reordered? I have tried looking for a solution but couldn't find one. Unlike the 'resizable' option, there doesn't seem to be an option for each column to allow or disal ...

Next.js Issue: Invariant error - page not correctly generated

I encountered a recurring error while attempting to build my project. Strangely, everything runs smoothly during development, but as soon as the build process is initiated, the following error presents itself: next build ▲ Next.js 14.1.0 - Environm ...

After toggling the switch to send the current state to the server, the React state remained unchanged

Could you clarify why the relay1 state is being sent as false? Why doesn't handleControlRelay1 change the state? Am I making a mistake by placing this inside a function? setRelay1((prevValue) => !prevValue); // ... const [relaysData, setRelaysD ...

Issue: You cannot render objects as a React child element (object found with properties {name}). If you intended to display multiple children, consider using an array instead

I have just finished creating a new Provider and now I want to test it. To do this, I am setting up a mock Component within the test file. // TasksProvider.spec.tsx const task = { name: 'New Task', } function TestComponent() { const { tasks ...

React-big-calendar: Customize day view to end at 1 am for multiple days

I'm currently in the process of developing a booking system and utilizing react-big-calendar for this project. Situation: A business operates from 9am to 2am the next day, allowing clients to book appointments between 11pm and 1am. Objective: To sho ...

Troubles arising while submitting data from AngularJS to Amazon S3

I am currently in the process of developing an application using the MEAN (MongoDB, Express, AngularJS, node.js) stack where I need to upload image files to Amazon S3. Here is my approach: Initially, an http get request is sent to my API which outlines th ...

The JQuery function assigning a value of 0 to the selectedIndex property is not functioning properly across all selected fields

<select name="wpcf-others" id="abc" class="myzebra-control myzebra-select"> <option value="wpcf-field123">General Work Jobs</option> <option value="wpcf-fields--1">Journalist/Editors Jobs</option> <option value="wpcf-4868b8 ...

Animating the height of a div using jQuery after loading dynamic content

When I load a page using AJAX, the content is represented as a string. I am then trying to animate the height of a container if the content is larger than the current height of the container. However, for some reason, the variable _height always ends up ...

The bar chart in chartjs is not displaying properly due to incorrect grouping

I attempted to generate a multi bar chart using Chart.js, but encountered an issue where the jobType and jobCount were not displayed correctly based on each companyName. Below is the table: https://i.sstatic.net/ZyKZH.png Here is the PHP file (CompanySel ...