What is the process for retrieving the checked ID from a checkbox, sending the selected ID to a URL using a query parameter, and then retrieving it in

I am working on a table that contains multiple fields,

My goal is to enable row selection using checkboxes.

name     Age      date
-----------------------
aaa      22       12-06-2019
bbb      23       13-06-2019
ccc      24       21-09-2019

In this scenario:

1. I need to be able to select rows using checkboxes.

2. Upon selecting a row, I should retrieve the unique ID associated with that row.

3. The selected IDs should then be included in a URL format like (), where 1, 2, and 3 represent the IDs of different fields.

4. Finally, I want to display and print these selected values.

Here are my questions:

  1. How can I retrieve the row's ID upon checkbox selection?

  2. What is the best way to print selected rows using Angular 8?

If anyone has any insights or guidance, please feel free to share!

Answer №1

View the live demonstration here

Inside the Class file:

data:

   list: any = [
        {id:1, 'name': 'aaa', 'age': 22, 'date': '12-06-2019'},
        {id:2, 'name': 'bbb', 'age': 23, 'date': '13-06-2019'},
        {id:3, 'name': 'ccc', 'age': 25, 'date': '21-09-2019'}
   ];

// Storing selected id in an array

checkedItems: any = [];

// Function to handle when user checks or unchecks a checkbox

 onChecked(item: any, event: any){
    let {checked, value} = event.target;
    if(checked) {
      this.checkedItems.push(value);
    } else {
      let index = this.checkedItems.indexOf(value);
      if (index !== -1) this.checkedItems.splice(index, 1);
    }
  }

To pass the selected item to the query parameter

 this.router.navigate(['/other'], {relativeTo: this.route, queryParams: { id: this.checkedItems.join() } });

Template file:

Iterating over the list and generating a table with checkboxes and binding onChange Event with its handler named onChecked

 <ng-container *ngFor="let item of list">
      <tr>
        <td>
          <input 
            type="checkbox" 
            [value]="item.id" 
            (change)="onChecked(item, $event)">
        </td>
        <td>{{item.name}}</td>
        <td>{{item.age}}</td>
        <td>{{item.date}}</td>
      </tr>
    </ng-container>

Answer №2

To include IDs in the query parameters of a URL, you can simply pass them along.

constructor(
  private router: Router,
  private route: ActivatedRoute,
) {}

changeQuery() {
  this.router.navigate(['.'], { relativeTo: this.route, queryParams: { ... }}); 
}

How do I retrieve the ID by selecting the checkbox?

You can achieve this by using the following code:

check(values, id){
  console.log(values.currentTarget.checked, id);
}
<tr *ngFor="let test of tests" >
  <td>
    <input type="checkbox" (change)="check($event, test.id)" [(ngModel)]="test.selected" > {{test.name}} - {{test.selected}}
  </td>
</tr>

How can I display the selected rows using Angular 8?

<div *ngFor="let row of selectedRows">
  <lable>row.col1</lable>
  <lable>row.col2</lable>
</div>

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

Performing a function call in Angular2 directly from an HTML element without the need for a load event or similar event

Being a beginner in Angular, I have encountered an issue that seems to require a javascript workaround which is not very elegant. I am dealing with a model that has an array property. I am using ngFor to generate HTML selection options based on this prope ...

The command 'npm cache clean' is failing to work in the Angular environment when using Visual Studio Code as the integrated

npm ERROR! Starting from npm@5, the npm cache will automatically fix any corruption issues and ensure that data extracted from the cache is always valid. To verify consistency, you can use 'npm cache verify' instead. npm ERROR! npm ERROR! ...

ionChange - only detect changes made in the view and update the model in Ionic 2

In my Ionic 2 application, I have a feature that allows users to schedule notifications as reminders. The requirements for this feature are as follows: Upon entering the reminder page, it should check if there is a saved reminder. If a reminder is saved ...

What are the steps to implementing AngularFireDatabase in Angular version 13?

I've been struggling to implement FirebaseDatabase in my Angular 13 project with the category.service.ts file. Despite trying various methods, I can't seem to get it to work properly. Here's the original sample code: import { AngularFireData ...

Issue arises with protractor peer dependencies during the installation of packages in Angular 13

Every time I try to install a new package, I encounter these errors in the console: (this instance involved trying to add ngx-bootstrap by running: ng add ngx-bootstrap npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While reso ...

Receiving an error while trying to install packages from the NPM registry due to non

I am facing some challenges while attempting to install my Ionic App through the registry along with its dependencies. I have been using npm i --loglevel verbose command, and my ~/.npmrc file is configured as follows: //nexus.OMMITED.com/repository/:_auth ...

What is the process for transforming an Object into a different type in this specific scenario?

Having an issue where I need to pass the data Object into a method, but it's saying that it doesn't have the hits property. Normally I would just use (data:any), however, since I also require the news data, that is not possible. Any suggestions o ...

When the webpage is reloaded in Internet Explorer, a file is automatically downloading. How can this issue be resolved?

Below is the anchor tag in HTML for downloading a file. <a [href]="myFileUrl" class="u-text--document" download="myfile.csv"><span>Title of the Excel document (6.8MB)</span></a> This method is called on n ...

Show information in two separate columns based on a specific criteria

In my current project with Angular, I am looking to present data in a two-column layout, with each row's placement determined by a specific condition. <div class="row" *ngFor="let content of Content"> <div class="col-md-6" *ngIf="conten ...

Troubleshooting problem with @Input number in Angular 2

Here is the component in question: <component value="3"></component> This is the code for the component: private _value:number; get value(): number { return this._value; } @Input() set value(value: number) { console.log(v ...

How can we dynamically update a type in Typescript based on the existence of a particular property after filtering?

My array contains the following information: const list: Readonly<ListProps> = {some values} interface ListProps { type: 'radio' | 'check'; style: 'text' | 'button'; options: OptionProps[]; } interface ...

Utilizing Angular 7, Ngrx, and Rxjs 6 to efficiently share state data among lazily loaded modules

Currently, I am working with Angular 7 alongside Ngrx and Rxjs 6. In my project, I have two lazy loaded modules named A and B, each with its own selectors and reducers. The challenge I am facing is accessing the data stored in module B's state from m ...

Bringing Typescript functions into the current module's scope

Is it possible to import and reference a module (a collection of functions) in typescript without the need for the Module. prefix? For instance: import * as Operations from './Operations'; Can I access Operations.example() simply as example()? ...

Errors persist with Angular 2 iFrame despite attempts at sanitization

Attempting to add an iFrame within my Angular 2 application has been challenging due to the error message that keeps popping up. unsafe value used in a resource URL context The goal is to create a dynamic URL to be passed as a parameter into the iFrame ...

The promise of returning a number is not compatible with a standalone number

I am currently working on a function that retrieves a number from a promise. The function getActualId is called from chrome.local.storage and returns a promise: function getActualId(){ return new Promise(function (resolve) { chrome.storage.syn ...

Disabling the intellisense feature for locale suggestions in Monaco is recommended

Switch the keyboard language to a different one (in this case Japanese using alt + shift), and when typing in Monaco editor, an intellisense menu appears with options to remove and search. Monaco Editor Version: V0.33.0 https://i.stack.imgur.com/SIyeV.pn ...

The FileLoader in Three.js does not have a constructor when passed through the scope manager

Although this question may appear to be a duplicate, as it is similar to this one and others, none of the solutions I have found have helped me resolve the issue. Therefore, I have decided to post it here in the hopes of finding a solution, as it is drivin ...

What is the best way to send a search parameter to a URL?

In my asp.net core web api, I developed a method that generates an object with the string provided in the URL. I now have a search form that needs to pass this string to the URL and retrieve the objects containing it. Here is how I utilize the api: impo ...

Typescript conditional types make room for the inclusion of null values

Consider this scenario involving conditional types: type MyType = 'Number' | 'String'; interface Test<T extends MyType> { bar: T extends 'Number' ? 25 : '25' } When attempting the following assignment: co ...

Encountering an unknown error with lite server when running npm start

A few weeks back, I was working on an Angular2 project and left it as is in the cloud. However, now when I try to run the project, I encounter an error right from the start. I suspect that the issue lies with lite-server, even though I have updated the no ...