You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular实现列头复选框一键控制列内所有复选框状态

Implement "Select All" Checkbox for Angular Table

Got it, let's get this bulk selection working for your table. The core idea is to sync the header checkbox state with all row checkboxes using Angular's data binding. Here's a step-by-step solution:

Step 1: Fix the HTML Template

First, we'll clean up duplicate IDs and add Angular bindings to handle the selection state:

<div class="Container">
  <div class="table-responsive">
    <table class="table">
      <thead class="table_header">
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Category</th>
          <th>Old date</th>
          <th>New date</th>
          <th>
            <input
              type="checkbox"
              id="select-all"
              [(ngModel)]="selectAll"
              (change)="toggleAllCheckboxes($event)"
            > Status
          </th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let form of formlist; index as i">
          <td>{{ form.id }}</td>
          <td>{{ form.name }}</td>
          <td>{{ form.cat }}</td>
          <td>{{ form.olddate }}</td>
          <td>{{ form.newdate }}</td>
          <td>
            <input
              type="checkbox"
              [id]="'checkbox-' + i"
              [(ngModel)]="form.isSelected"
              (change)="updateSelectAllCheckbox()"
            >
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

Key HTML Changes:

  • Added [(ngModel)]="selectAll" to the header checkbox to track its state
  • Added (change)="toggleAllCheckboxes($event)" to trigger bulk selection logic
  • For row checkboxes:
    • Used dynamic ID [id]="'checkbox-' + i" to avoid duplicate IDs (critical for valid DOM)
    • Bound each checkbox to form.isSelected (we'll add this property next)
    • Added (change)="updateSelectAllCheckbox()" to sync the header checkbox when rows are manually selected/deselected

Step 2: Update Component TypeScript Code

Now, add the necessary properties and methods to your Angular component:

import { Component } from '@angular/core';

// Define an interface for your form objects (adjust to match your actual data)
interface FormItem {
  id: number;
  name: string;
  cat: string;
  olddate: string;
  newdate: string;
  isSelected: boolean; // Tracks row selection state
}

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponentComponent {
  formlist: FormItem[] = [];
  selectAll = false;

  // Initialize your form data (replace with your actual data fetch logic)
  ngOnInit() {
    this.formlist = [
      { id: 1, name: 'Form 1', cat: 'Category A', olddate: '2023-01-01', newdate: '2024-01-01', isSelected: false },
      { id: 2, name: 'Form 2', cat: 'Category B', olddate: '2023-02-01', newdate: '2024-02-01', isSelected: false },
      // Add more items as needed
    ];
  }

  // Toggle all row checkboxes when header checkbox changes
  toggleAllCheckboxes(event: Event) {
    const isChecked = (event.target as HTMLInputElement).checked;
    this.formlist.forEach(form => {
      form.isSelected = isChecked;
    });
  }

  // Update header checkbox state when any row checkbox changes
  updateSelectAllCheckbox() {
    this.selectAll = this.formlist.every(form => form.isSelected);
  }
}

Key TS Changes:

  • Added isSelected property to your form interface to track each row's selection state
  • Added selectAll property to track the header checkbox state
  • toggleAllCheckboxes(): Iterates over all form items and sets their isSelected state to match the header checkbox
  • updateSelectAllCheckbox(): Checks if all rows are selected, and updates the header checkbox accordingly (so if you manually select all rows, the header checkbox checks itself)

Step 3: Import FormsModule

Don't forget to import FormsModule in your module (e.g., AppModule) to use ngModel:

import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // Other imports
    FormsModule
  ]
})
export class AppModule { }

That's it! Now when you check the header "Status" checkbox, all row checkboxes will sync to checked, and vice versa. Plus, manual selection/unselection of rows will update the header checkbox to reflect whether all rows are selected.

内容的提问来源于stack exchange,提问作者Expert Labs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 21:12:27