【发布时间】:2019-12-09 06:59:38
【问题描述】:
我正在 Angular 8 中创建一个应用程序。
我的应用程序使用一个对话框来显示一个包含产品数据的表格,该表格显示两列 [id, description],如您所见,id 列生成一个复选框并为每个产品打印和 id。
这是生成每个复选框并打印表格中的 id 的代码:
<ng-container matColumnDef="Id">
<th mat-header-cell *matHeaderCellDef>Id</th>
<td mat-cell *matCellDef="let element">
//I assign an id to each checkbox which is the one of the element to show (A, B, C... etc)
// and bind the method change to 'checkboxChanged', this event lets me to push the id of the checkbox to an array
<mat-checkbox (change)="checkboxChanged($event)" id={{element.id}}>
{{element.id}}
</mat-checkbox>
</td>
</ng-container>
<ng-container matColumnDef="Description">
<th mat-header-cell *matHeaderCellDef>Description</th>
<td mat-cell *matCellDef="let element">{{element.description}}</td>
</ng-container>
当用户点击每个复选框时,会触发一个名为“checkboxChanged”的函数来添加/删除数组中的 id(取决于复选框的状态)。
这是将复选框添加到数组的逻辑代码:
public tempData = [];
checkboxChanged(event) {
const id = event.source.id; //Get the id of the checkbox
console.log(event.checked); //true or false
console.log(id); //A, B, C... etc
if (event.checked) this.tempData.push(id); //If checked, add to array
else { //if unchecked, remove from the array
const i = this.tempData.indexOf(id);
this.tempData.splice(i, 1);
}
console.log("tempData", this.tempData); // prinst [B, C] from the example of the screenshot
}
用户点击他们想要的产品的所有复选框后,他们可以点击“添加”将数组发送到主屏幕,然后进行处理。例如,如果用户点击 B 和 C 作为截图,则数组为 [B, C]。
问题是这个对话框使用Angular Material Pagination,所以每次用户更改页面时,所有复选框都默认变为未选中,所以,如果我点击A和B,转到第二页然后返回对于第一个,A 和 B 复选框将被取消选中,但数组仍将是 [A, B]。
我对此的设想是在生成每个复选框时创建一个条件,这样我是否移动到其他页面都没关系。这个条件应该是'如果 Id 已经存在于 tempData 中,则检查 ckeckbox',类似于:
<mat-checkbox (change)="checkboxChanged($event)" id={{element.id}} checked = "{{this.tempData}}.includes({{element.id}})">
{{element.id}}
</mat-checkbox>
所以这里的中心点是发现如何应用这个条件,可能是通过 *ngIf 或通过复选框的 'checked' 属性。
有人可以帮帮我吗?:(
【问题讨论】:
标签: javascript angular checkbox pagination angular8