【问题标题】:Angular5 Need function to check/uncheck mat-checkbox inside mat-tableAngular5需要功能来检查/取消选中mat-table中的mat-checkbox
【发布时间】:2018-06-11 07:58:19
【问题描述】:

我可以在表格中获得复选框以在选中/取消选中时发出更改,但是在单击地图图钉以切换复选框状态时遇到麻烦。

my table with map

这是我的桌子:

      <mat-table [dataSource]="dataSource">
        <ng-container matColumnDef="number">
          <mat-header-cell *matHeaderCellDef> Number </mat-header-cell>
          <mat-cell *matCellDef="let stock">
            // #myCheckbox needs to be unique
            <mat-checkbox #myCheckbox [checked] (change)="selectStock(stock, $event)"></mat-checkbox> <a href="">{{ stock.number }}</a>
          </mat-cell>
        </ng-container>
        <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
        <mat-row *matRowDef="let row; columns: displayedColumns;" (click)="clickRow(row._id,$event)"></mat-row>
      </mat-table> 

然后在我的地图上,当你点击一个图钉时,运行一些函数

  (click)="someFunction(myCheckbox)"

在我的课堂上

    @ViewChild('myCheckbox') private myCheckbox: MatCheckbox;

    someFunction(myCheckbox){
         if (stock.isChecked) {
            this.myCheckbox.checked = false;
            } else {
            this.myCheckbox.checked = true;
         }
    }        

这是我正在处理的示例,但它对每个复选框应用相同的#id,因此只有第一个复选框被切换(我假设我需要每个复选框唯一的唯一 ID?)

【问题讨论】:

  • 还有没有可能你的 selectStock 函数代码?

标签: angular local-variables ngfor angular5


【解决方案1】:

在网站上进行更多搜索后,我能够使用 ViewChildren 解决问题

好东西

【讨论】:

  • myCheckboxes[index].checked = item.isChecked;,节省一些代码行:)
【解决方案2】:

下面是一个完整的工作示例。在类实现TypeScript-File中:

import { Component, OnInit, Inject, EventEmitter, Output, OnDestroy, QueryList, ViewChildren } from '@angular/core';

...    

export class YourClassName implements OnInit, OnDestroy {

    ...

    selectables : Array<string> = ['ah','be','ce'];
    @ViewChildren('checkboxMultiple') private checkboxesMultiple : QueryList<any>;

    ...

    selectionChange( event ) : void {

        // get index from template loop or so. In this case the value
        // of the mat-checkbox is an Array with the value as first and
        // the loop index as second entry
        let index = event.source.value[1];
        let checkboxesArray = this.checkboxesMultiple.toArray();
        checkboxesArray[index].checked = false;

        // You could also loop over all checkboxes and check/uncheck
        // them based on your logic
    }
}

在你的模板文件中:

...

<mat-checkbox #checkboxMultiple
        *ngFor="let selectable of selectables; let i = index"
        (change)="selectionChange($event)"
        [value]="[selectable, i]">
        {{ selectable }}&nbsp;&nbsp;
</mat-checkbox>

我发现你必须使用 QueryList 对象的 toArray() 方法来获取实际的复选框数组。

【讨论】:

    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-08
    • 2021-10-07
    • 1970-01-01
    相关资源
    最近更新 更多