使用角度 2

问题描述 投票:0回答:1

`我正在尝试创建一个复选框,一旦选中,它就会选中 div 中的所有复选框。 div 只包含复选框。

//TS 文件

 constructor() { }
 
  checkAll: ElementRef | undefined;
  selectAll(isChecked: boolean){
  `your text`this.checkboxes.forEach(this.checkboxes = this.checkboxes.checked = isChecked)};

 checkboxes = this.checkAll.nativeElement.parentElement.querySelectorAll('input[type="checkbox"]');

 ngOnInit(): void {
}

//HTML 文件

                 <label
                  for="inputFirstName"
                  class=""
                  id="select-all-checkbox"
                  #checkAll 
                  (check)="selectAll(checkAll.checked)"
                  >Select all</label
                >
                <input
                  type="checkbox"
                  id="selectall"
                  class="mx-4"
                  style="width: 20px; height: 20px; border-radius: 3px"`your text`
                />

`

html angular typescript forms checkbox
1个回答
0
投票

可以导入选择模型

import {SelectionModel} from "@angular/cdk/collections";

    <input
                  type="checkbox"
                  id="selectall" #selectAllCheckBox
style="width: 20px; height: 20px; border-radius: 3px"
(change)="selectAll(selectAllCheckBox.checked)"
                  class="mx-4" 
                  />

在.ts

constructor(private checkAll: ElementRef) {}
      ngOnInit() {
        this.checkboxes = this.checkAll.nativeElement.querySelectorAll(
          'input[type="checkbox"]'
        );
      }
      selectAll(isChecked) {
        this.checkboxes.forEach(chekbox => {
          chekbox.checked = isChecked;
        });
      }
© www.soinside.com 2019 - 2024. All rights reserved.