Guide on transferring data from one table to another by choosing one or multiple rows with the help of Angular 2

https://i.sstatic.net/CF1Xo.pngHello, I'm currently facing an issue with my requirements. I'm attempting to display two tables.

Data for Table One:

TableOne =[
  {
    "Id": 1,
    "Name": "ONLINE",
    "Status": false,
    "Track": false,
  },
  {
    "Id": 2,
    "Name": "ONLINE",
    "Status": false,
    "Track": true,
  },
  {
    "Id": 3,
    "Name": "DEAL",
    "Status": true,
    "Track": false,

  },
  {
    "Id": 4,
    "Name": "OFFLINE",
    "Status": false,
    "Track": false,

  },

]

Data for Table Two:

Tab =[
  {
    "Id": 1,
    "Name": "ONLINE",
    "Status": false,
    "Track": false,
  },
  {
    "Id": 2,
    "Name": "ONLINE",
    "Status": true,
    "Track": false,
  },
  {
    "Id": 3,
    "Name": "DEAL",
    "Status": true,
    "Track": false,

  },
]

Table one:

Id  Name    Status  Track
1   ONLINE      false
2   ONLINE      true
3   DEAL        false
4   OFFLINE     false
Table two:

Id  Name    Status  Track
1   ONLINE      false
2   ONLINE      false
3   DEAL        false

The issue I am encountering is: How can I retrieve values from selected table rows using checkbox selection? And how can I transfer the selected values from table one to table two by clicking a button? Also

  1. Selecting rows from table one and moving them to table two
  2. If table one has the name "Online" and table two has the name "Offline" with the same id number, will it overwrite?
  3. Upon clicking the button, how can I access the values of the selected row(s)?

Below is the link to my StackBlitz project.

Answer №1

Revised as per feedback:

1

To begin with, we need to establish arrays that will hold the selected items from each table:

  readonly TableOneSelections = [];
  readonly TabSelections = [];

Once a user checks or unchecks a record, a function will be invoked to add or remove the record from the selection list

  <input type="checkbox" (change)="onSelectionChanged($event, D, TableOne)"></td> //first table
  <input type="checkbox" (change)="onSelectionChanged($event, D, Tab)"></td> //second table

Function logic:

  onSelectionChanged(event, record, table) {
    const selections = table === this.TableOne ? this.TableOneSelections : this.TabSelections;
    event.target.checked
      ? selections.push(record)
      : selections.splice(selections.findIndex(selection => selection.Id === record.Id), 1)
  }

Following that, buttons can be created for moving selected records. When clicked, each button will trigger the moveSelectedRecords function to transfer the selected records to another table.

<button (click)="moveSelectedRecords(TableOne, Tab)">Move down</button> //first table
<button (click)="moveSelectedRecords(Tab, TableOne)">Move up</button> //second table

Implementation of moveSelectedRecords function:

  moveSelectedRecords(fromTable: any[], toTable: any[]) {
    const selections = fromTable === this.TableOne ? this.TableOneSelections : this.TabSelections;
    selections.forEach(selectedRecord => {
      const removedRecordIndex = fromTable.findIndex(record => record === selectedRecord);
      const removedRecord = fromTable.splice(removedRecordIndex, 1)[0];
      toTable.push(removedRecord);
    });
    selections.length = 0;
  }

2

If there is a need to overwrite records with the same Id, a slightly modified function named moveAndOverwriteSelectedRecords can be used:

  moveAndOverwriteSelectedRecords(fromTable: any[], toTable: any[]) {
    const selections = fromTable === this.TableOne ? this.TableOneSelections : this.TabSelections;
    selections.forEach(selectedRecord => {
      const removedRecordIndex = fromTable.findIndex(record => record === selectedRecord);
      const removedRecord = fromTable.splice(removedRecordIndex, 1)[0];
      const indexInSecondTable = toTable.findIndex(record => record.Id === removedRecord.Id);
      indexInSecondTable !== -1
        ? toTable[indexInSecondTable] = removedRecord
        : toTable.push(removedRecord)
    });
    selections.length = 0;
  }

3

Additionally, buttons can be created to invoke the getSelectedRecords function for a specific table:

<button (click)="getSelectedRecords(TableOne)">Get selected records</button> //first table
<button (click)="getSelectedRecords(Tab)">Get selected records</button> // second table

Within the function, you can access the selection arrays

  getSelectedRecords(fromTable: any[]) {
    const selections = fromTable === this.TableOne ? this.TableOneSelections : this.TabSelections;
    console.log(selections)
  }

Check out the live demo: https://stackblitz.com/edit/angular-d1smii

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

Having trouble accessing input value when using FormArrayName with FormBuilder?

When attempting to retrieve the value from the input field using formArrayName, I am encountering an issue where it returns null instead. The console shows that I can get the value for client name but not for secrets. What I need is for the returned value ...

Record modified fields using Angular Reactive Forms and store them in a list

Is there a method available that can identify and return the fields that have been modified within a form? I am looking to generate a list of string values for the changed fields. I am dealing with a complex form containing approximately 30 different fiel ...

What is the best way to integrate Nextjs Link Component with framer motion in a Typescript environment?

Description I am trying to use Framer Motion to animate a Next.js Link component in a TypeScript environment, but I keep encountering a type error: Property 'Link' does not exist on type '(<Props extends {}>(Component: string | Compo ...

Steps to trigger pipe activation in Angular when the model is updated:1. Execute the

I have a unique filter pipe that allows me to filter an array of objects. This filter pipe has a dependency injection through a service. The service contains the model data filterService.data. Is there a way to activate this pipe in the template only when ...

Looping through NavItems component using JavaScript or Angular

My Angular project includes a navbar component with an app sidebar that has a navItems attribute. Below is the content of my navBar: <app-header style="background-color : #e65100;" [fixed]="true" [navbarBrandFull]="{ src: &a ...

The Typescript error "Attempting to call a function that does not have any callable signatures.(2349)"

Could you please assist me in resolving this issue: type IValidator = (value?: string) => string | undefined; type IComposeValidators = (validators: ((value?: string) => string | undefined)[]) => IValidator; export const composeValidators: ICompo ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

Verify web connectivity in an Angular2 (non-Ionic) Cordova application

Our team has developed an Angular2 Cordova application (not Ionic) that interacts with multiple backend services. We want the app to display a specific page (Component) if a user is offline. Although we have already created this feature, we are unsure of ...

Looking to conceal the input div without compromising the functionality in Angular 14

Here is the provided HTML code for scanning a barcoder and assigning it to the barCodeNumber variable. The onChange() function will be called once the barcode is scanned. Question: How can I hide the div on the UI while still allowing the function to work ...

Retrieve the non-empty attributes of a JSON object

I have a function in Typescript that extracts specific values from a JSON data object, some of which may be empty. How can I retrieve only certain data fields? Here is the function: let datosCod; for (let get in Object.keys(transfConsData)) { co ...

After saving any HTML, SCSS, or TS file, Angular 12 does not compile immediately

Recently I upgraded my Angular project from version 8 to 12 and then migrated to eslint. However, I have encountered an issue where the compilation does not begin immediately after saving a file. There is a delay of approximately 2 minutes before the compi ...

In the domain of React and Typescript, a minimum of '3' arguments is anticipated; nonetheless, the JSX factory 'React.createElement' is only equipped with a maximum of '2' arguments. This incongruity is signaled by the

I am facing an error with this particular component: const TheBarTitle = ( theClass: any, columnTitle: string, onClickAction: any, ) => { return ( <div className={theClass} title="Click to add this ...

Achieving JSON element sorting in the most effective way

https://i.stack.imgur.com/NQbdN.png Each array contains the following information: {{ id: 39, treaty_number: "qwe", insurant_name: "222", belonging_to_the_holding_company: "test", date_start: "2016-04-15", etc }} Is there a way to sort each array in asc ...

Angular HTTP post call is failing to redirect to the correct URL

https://i.sstatic.net/CzSuQ.pngCan someone assist me in resolving the http post problem? I am facing an issue where the url validation is not working correctly. Even when localhost:8084 is up and running, the error section is triggered, and the same happen ...

The FullCalendarModule does not have a property named 'registerPlugins' in its type definition

Currently in the process of integrating fullcalendar into my Angular 15 project and encountering the following error: Error: src/app/views/pages/takvim/takvim.module.ts:18:20 - error TS2339: Property 'registerPlugins' does not exist on type &apo ...

Is the Angular 7 router '**' wildcard feature failing to work properly when used in conjunction with lazy loaded modules and child routes?

I'm currently working on setting up a default route using the wildcard '**' with Angular's router. The intention is for this default route to load a lazy module and then handle its own routes internally. However, I have run into an issu ...

Warning: The gulp_jspm module is now deprecated and will be removed

Whenever I run gulp_jspm, a DeprecationWarning pops up. Is there an alternative method to generate my bundle files without encountering this warning? It seems like when I used gulp-jspm-build, I had to include some node files that were not necessary before ...

What steps can be taken to resolve the error message "Module '../home/featuredRooms' cannot be found, or its corresponding type declarations"?

Upon deploying my site to Netlify or Vercel, I encountered a strange error. The project runs smoothly on my computer but seems to have issues when deployed. I am using TypeScript with Next.js and even attempted renaming folders to lowercase. Feel free to ...

Is Webpack CLI causing issues when trying to run it on a .ts file without giving any error

I am facing an issue with my webpack.config.js file that has a default entrypoint specified. Here is the snippet of the configuration: module.exports = { entry: { main: path.resolve('./src/main.ts'), }, module: { rules: [ { ...

How to properly handle sending an empty post request in Angular 2

My current issue revolves around attempting to send data from my application to the server using a POST request, however, the server seems to be receiving empty POST data. This is the function responsible for sending the data: private headers = new Heade ...