In my project, I have a list of users stored in an array. Using HTML, I utilized the *ngFor directive to create a checkbox for each user element. Additionally, there is an @Input assignedAccountIds[] which contains the IDs of default selected users.
The code snippet for the checkbox element looks like this:
<mat-checkbox
color="primary"
[disabled]="disableCurrentAccountCheckbox && account.id === currentAccountId"
[checked]="isAccountSelected(account)"
(change)="onSelectAccount($event, account)"
>
The method isAccountSelected determines whether a user is included in the selected items array to decide if the checkbox should be checked or not. Here is its implementation:
isAccountSelected(account: ClientAccount): boolean {
return (this.assignedAccountIds || []).includes(account.id);
}
When the change event occurs, the onSelectAccount method handles it as shown below:
onSelectAccount(event: MatCheckboxChange, account: ClientAccount): void {
if (
!event.checked &&
this.currentAccountId &&
account.id === this.currentAccountId
) {
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
data: {
message: `You will not be able to see this inspection if you unassign yourself!`,
buttonColor: 'primary',
buttonLabel: 'Unassign',
},
position: {
right: '10px',
bottom: '10px',
},
maxWidth: '580px',
});
dialogRef
.afterClosed()
.pipe(untilDestroyed(this))
.subscribe(result => console.log(result));
} else {
this.selectionChange.emit({ id: account.id, checked: event.checked });
}
}
Essentially, I am implementing a feature that triggers a confirmation modal when a user attempts to unselect themselves from the list. The checkbox state will only change based on the user's selection (Yes/No) in the modal dialogue.