mercredi 31 juillet 2019

Make a checkbox checked if its id is present in an array

I'm creating an app in Angular 8.

My app uses a dialog to show a table which contains data about products, the table shows two columns [id, description], as you can see, the id column generates a checkbox and prints and id for each product.

enter image description here

This is the code that generates each checkbox and prints the ids in the table:

<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=>
            
        </mat-checkbox>
    </td>
</ng-container>
<ng-container matColumnDef="Description">
    <th mat-header-cell *matHeaderCellDef>Description</th>
    <td mat-cell *matCellDef="let element"></td>
</ng-container>

When the user clicks on each checkbox, a function called 'checkboxChanged' is fired to add/remove the id in a array (depending on the state of the checkbox).

This is the code for the logic to add the checkbox to an array:

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 
}

After the user clicks on all the checkboxs of the products they want, they can click on 'add' to send the array to the principal screen and then process it. E. G. if the user clicks on B and C as the screenshot, the array is [B, C].

The matter is that this dialog uses Angular Material Pagination, so each time the user changes the page all the checkboxes are turn to unchecked as default, so, if I click on A and B, turn to the 2nd page and then return to the first one, the A and B checkboxes will be unchecked but the array will still be [A, B].

What I imagine for this is to make a condition when generating each checkbox so it doesn't matter if I move to another pages. This condition should be 'if the Id already exist in tempData then check the ckeckbox', something like:

<mat-checkbox (change)="checkboxChanged($event)" id= checked = ".includes()">
    
</mat-checkbox>

So the central point here is to discover how to apply this condition, maybe through an *ngIf or through the 'checked' property of the checkbox.

Could anybody help me please?:(




Aucun commentaire:

Enregistrer un commentaire