Angular 2中复选框选中时向textarea添加选项数组的问题
Got it, let's get this sorted for you. The main issue here is that you're not maintaining a persistent list of selected items—right now, you're probably overwriting the textarea value each time you click a checkbox, and your remove logic isn't correctly updating that list. Here's a clean Angular solution that handles both selecting and deselecting properly:
Component TypeScript Code
import { Component } from '@angular/core'; @Component({ selector: 'app-checkbox-list', templateUrl: './checkbox-list.component.html', styleUrls: ['./checkbox-list.component.css'] }) export class CheckboxListComponent { // Your existing item list (adjust the structure to match your actual data) itemList = [ { name: 'Option A' }, { name: 'Option B' }, { name: 'Option C' } ]; // Array to track all selected item names (this is our source of truth) selectedItems: string[] = []; onCheckboxChange(item: any, event: Event): void { const checkbox = event.target as HTMLInputElement; const itemName = item.name; if (checkbox.checked) { // Add the item only if it's not already in the array (prevents duplicates) if (!this.selectedItems.includes(itemName)) { this.selectedItems.push(itemName); } } else { // Remove the item by filtering it out of the array this.selectedItems = this.selectedItems.filter(name => name !== itemName); } } }
Template HTML Code
<div *ngFor="let items of itemList"> <div class="xxx"> <input type="checkbox" (change)="onCheckboxChange(items, $event)" <!-- Optional: Keep checkboxes checked if their name is in selectedItems --> [checked]="selectedItems.includes(items.name)" > <label>{{ items.name }}</label> </div> </div> <!-- Bind the textarea value to our joined selected items array --> <textarea rows="4" cols="50" [value]="selectedItems.join(', ') <!-- Replace ', ' with '\n' for new lines per item --> ></textarea>
Key Fixes & Explanations
selectedItemsArray: This acts as the single source of truth for all checked items. Instead of updating the textarea directly, we update this array, and the textarea reflects its state.onCheckboxChangeMethod:- When checking a box, we add the item's name only if it's not already present (avoids duplicate entries).
- When unchecking, we filter the array to remove the item's name entirely, ensuring it's no longer displayed.
- Textarea Binding: Using
[value]="selectedItems.join(', ')"converts the array of names into a readable string. Swap', 'with'\n'if you want each selected name on a new line. - Optional
[checked]Binding: This ensures checkboxes stay checked if their name is inselectedItems(useful for component re-renders or page reloads).
内容的提问来源于stack exchange,提问作者niraja k
相关产品推荐
相关产品推荐

