我可以在表格中获取复选框以在选中/取消选中时发出更改,但是在点击地图引脚切换复选框状态时遇到麻烦。
这是我的表:
<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?)
答案 0 :(得分:5)
在网站上搜索更多内容之后,我能够使用ViewChildren
解决问题angular4 local variable issue for *ngFor
@ViewChildren('myCheckbox') private myCheckboxes : QueryList<any>;
someFunction(item, index){
let myCheckboxes = this.myCheckboxes.toArray();
if (item.isChecked) {
myCheckboxes[index].checked = true;
} else {
myCheckboxes[index].checked = false;
}
}
好东西
答案 1 :(得分:0)
下面是一个完整的有效示例。在类实现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 }}
</mat-checkbox>
我发现您必须使用QueryList对象的toArray()方法来获取复选框的实际数组。