选中一个复选框,检查其ID是否存在于数组中

时间:2019-07-31 17:29:19

标签: javascript angular checkbox pagination angular8

我正在Angular 8中创建一个应用。

我的应用程序使用一个对话框显示一个包含产品数据的表,该表显示两列[id,description],如您所见,id列生成一个复选框并为每个产品打印和ID。

enter image description here

这是生成每个复选框并在表中打印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 
}

用户单击所需产品的所有复选框后,可以单击“添加”以将阵列发送到主体屏幕,然后进行处理。 E. G.如果用户单击B和C作为屏幕截图,则数组为[B,C]。

问题在于此对话框使用“角度材质分页”,因此,每次用户更改页面时,默认情况下,所有复选框都将变为未选中状态,因此,如果我单击A和B,则转到第二页,然后返回到第一个,将不选中A和B复选框,但数组仍为[A,B]。

我为此设想的是在生成每个复选框时创造一个条件,因此无论我是否移至其他页面都没有关系。此条件应为“如果tempData中已经存在ID,则检查ckeckbox”,例如:

<mat-checkbox (change)="checkboxChanged($event)" id={{element.id}} checked = "{{this.tempData}}.includes({{element.id}})">
    {{element.id}}
</mat-checkbox>

所以这里的中心点是发现如何应用此条件,可能是通过* ngIf还是通过复选框的'checked'属性。

有人可以帮我吗?:(

1 个答案:

答案 0 :(得分: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的数组,则必须工作