【问题标题】:Make a checkbox checked if its id is present in an array如果其 id 存在于数组中,请选中复选框
【发布时间】: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


    【解决方案1】:

    试试这个解决方案

    <mat-checkbox (change)="checkboxChanged($event)" id={{element.id}} [checked] = "toggleCheckBox(element.id)"> {{element.id}} </mat-checkbox>

    在你的 .ts 中创建这个函数

    toggleCheckBox(elementId){ return (this.tempData.indexOf(elementId) != -1) ? true : false; }

    如果你的变量 tempData 是一个 id 数组,它必须工作

    【讨论】:

    • 请不要这样做。
    • @bryan60 你为什么这么说?
    • 模板函数调用是性能噩梦。这将评估每个变更检测周期
    • 您会推荐什么资源/机制来代替?我对此很感兴趣
    • 我知道我迟到了......但有几件事:A)如果你使用 ChangeDetectionStrategy.OnPush 性能问题不是那么大......和 ​​B)而不是有一个数组您维护的选定项目,您可以在您的项目上有一个“选定”属性并将其绑定到您的复选框。然后,当您要执行操作时,从 selected=true 的项目中获取 id 并创建数组。如果您使用的是不可变数据,请小心
    猜你喜欢
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 2020-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多