点击按钮时如何获取多个复选框的值?(Ionic/Angular场景)
Hey there! Let's fix this step by step so you can grab all selected car IDs when clicking that duplicate button.
First, let's address the key issues in your current code:
1. Fix selector typos and get all checked boxes
Your current function uses document.querySelector('.messageCheckbox:checked'), but your checkboxes have the class checkbox (not messageCheckbox). Also, querySelector only returns the first matching element—you need querySelectorAll to collect all checked boxes.
2. Correct value binding in your HTML
Right now, your checkbox's value is set to the string "Cars.id" instead of the actual Cars.id variable. Use Angular's property binding to pass the real ID value:
<td><p><input class="checkbox" type="checkbox" [value]="Cars.id"> </p></td> <button (click)="duplicate()"><ion-icon name="color-wand"></ion-icon></button>
3. Update the duplicate() function to collect all IDs
Here's the fixed vanilla JS version that will capture all selected IDs:
duplicate() { // Get all checked checkboxes with the correct class const checkedCheckboxes = document.querySelectorAll('.checkbox:checked'); // Convert the NodeList to an array and extract values const selectedCarIds = Array.from(checkedCheckboxes).map(checkbox => checkbox.value); // Now you have an array of all selected Cars.id values console.log('Selected car IDs:', selectedCarIds); }
(Recommended) Angular-friendly approach using ViewChildren
While the above works, using document queries in Angular can be unreliable for dynamic DOM changes. Instead, use Angular's ViewChildren to reference checkboxes directly:
Step 1: Add a template reference to your checkboxes
<td><p><input #carCheckbox class="checkbox" type="checkbox" [value]="Cars.id"> </p></td>
Step 2: Import and use ViewChildren in your component
import { Component, ViewChildren, QueryList, ElementRef } from '@angular/core'; @Component({ // Your component metadata (selector, template, etc.) here }) export class YourComponent { @ViewChildren('carCheckbox') carCheckboxes!: QueryList<ElementRef>; duplicate() { const selectedCarIds = this.carCheckboxes.toArray() .filter(checkboxEl => checkboxEl.nativeElement.checked) .map(checkboxEl => checkboxEl.nativeElement.value); console.log('Selected car IDs:', selectedCarIds); } }
This approach is more aligned with Angular best practices and avoids potential issues with DOM manipulation outside Angular's context.
内容的提问来源于stack exchange,提问作者Sahil

