Below is the component of the code.
import { CommonModule } from '@angular/common';
import { MatIconModule } from '@angular/material/icon';
import { ApiService } from 'src/app/services/api/api.service';
import {
SNACKBAR_TYPES,
SnackbarService,
} from 'src/app/services/snackbar/snackbar.service';
import { TokenService } from 'src/app/services/token/token.service';
import { DialogRef } from '@angular/cdk/dialog';
import { SharedModule } from 'src/app/shared/shared.module';
import { MatFormFieldModule } from '@angular/material/form-field';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatInputModule } from '@angular/material/input';
import { MAT_DIALOG_DATA, MatDialogModule } from '@angular/material/dialog';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatSelectModule } from '@angular/material/select';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { BehaviorSubject } from 'rxjs';
import { MatTableDataSource, MatTableModule } from '@angular/material/table';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { WalletUser } from 'src/app/profile/profile.component';
export interface Pagination {
pageIndex: number;
pageSize: number;
count: number;
data: Role[];
}
export interface User {
id: string;
phone: string;
name: string;
isActive: boolean;
jpAuthId: string;
addedByName: string;
createdAt: string;
updatedAt: string;
roles: Role[];
}
export interface Role {
id: string;
name: string;
isActive: boolean;
createdAt: string;
updatedAt: string;
}
@Component({
selector: 'app-manage-user-roles',
standalone: true,
imports: [
CommonModule,
MatIconModule,
MatTableModule,
SharedModule,
MatFormFieldModule,
FormsModule,
ReactiveFormsModule,
MatInputModule,
MatDialogModule,
MatIconModule,
MatProgressSpinnerModule,
MatSelectModule,
MatAutocompleteModule,
MatProgressBarModule,
],
templateUrl: './manage-user-roles.component.html',
styleUrls: ['./manage-user-roles.component.scss'],
})
export class ManageUserRolesComponent {
loading: boolean;
isLoadingRoles!: boolean;
userRoles: Role[] = [];
pageSize: number = 10;
pageIndex: number = 0;
userId: string;
availableRoles: BehaviorSubject<Role[]> = new BehaviorSubject<Role[]>([]);
displayedColumns: string[] = ['name', 'actions'];
roles: Role[] = [];
rolesAssignedToUserHas: any;
user: WalletUser | null = null;
dataSource: MatTableDataSource<Role> = new MatTableDataSource<Role>();
rolesUpdated: EventEmitter<void> = new EventEmitter<void>();
constructor(
private api: ApiService,
private snackbar: SnackbarService,
@Inject(MAT_DIALOG_DATA) public userData: User,
private dialogRef: DialogRef
) {
this.getUserRoles(this.pageSize, this.pageIndex);
this.rolesAUserHas(this.userId);
}
getUserRoles(limit: number, offset: number) {
this.api.get_roles((limit = 20), (offset = offset)).subscribe({
next: (data: any) => {
this.roles = data.data;
console.log(this.roles, 'roles-------------------------->');
this.dataSource.data = this.roles;
},
error: (error) => {
this.loading = false;
let errMsg: string = error.error.message;
switch (error.status) {
case 403:
errMsg = 'You are not allowed to perform this action.';
break;
default:
break;
}
this.snackbar.openSnackBar(
'Error: ' + errMsg,
'OK',
5,
SNACKBAR_TYPES.Danger
);
},
complete: () => {
this.loading = false;
},
});
}
closeDialog(): void {
this.dialogRef.close();
}
rolesAUserHas(userId: string): void {
userId = this.userData.id;
this.api.getRolesAssignedToUser(userId).subscribe({
next: (data: any) => {
this.rolesAssignedToUserHas = data.data;
console.log(
this.rolesAssignedToUserHas,
'roles a user has---------------------->'
);
},
error: (error) => {
this.loading = false;
let errMsg: string = error.error.message;
this.snackbar.openSnackBar(
'Error: ' + errMsg,
'OK',
5,
SNACKBAR_TYPES.Danger
);
},
complete: () => {
this.loading = false;
},
});
}
assignOrRevokeRole(roleId: string): void {
this.toggleIsLoading();
const hasRole = this.userData.roles.some((role) => role.id === roleId);
if (hasRole) {
this.revokeRole(roleId);
} else {
this.assignRole(roleId);
}
}
assignRole(roleId: string): void {
this.api
.assignRole({
userId: this.userData.id,
roleId: roleId,
status: false,
})
.subscribe({
next: (res) => {
console.log(res);
this.toggleIsLoading();
this.snackbar.openSnackBar(
'Role assigned successfully',
SNACKBAR_TYPES.Success
);
const role = this.roles.find((r) => r.id === roleId);
if (role) {
this.userData.roles.push(role);
}
this.rolesUpdated.emit();
},
error: (error) => {
console.log(error);
this.toggleIsLoading();
this.snackbar.openSnackBar(
'Error Assigning Role: ' + error.error.message.join('n') ||
error.message,
'Close',
3,
SNACKBAR_TYPES.Danger
);
},
});
}
revokeRole(roleId: string): void {
this.api.revokeRole(roleId).subscribe({
next: (res) => {
console.log(res);
this.toggleIsLoading();
this.snackbar.openSnackBar(
'Role revoked successfully',
SNACKBAR_TYPES.Success
);
this.userData.roles = this.userData.roles.filter(
(role) => role.id !== roleId
);
this.rolesUpdated.emit();
},
error: (error) => {
console.log(error);
this.toggleIsLoading();
this.snackbar.openSnackBar(
'Error Revoking Role: ' + error.error.message.join('n') ||
error.message,
'Close',
3,
SNACKBAR_TYPES.Danger
);
},
});
}
roleIsIncluded(roleId: string): boolean {
return this.roles?.some((role) => role.id === roleId);
}
private toggleIsLoadingRoles(): void {
this.isLoadingRoles = !this.isLoadingRoles;
}
private toggleIsLoading(): void {
this.loading = !this.loading;
}
}
Below is the template code of the component
<div class="p-5">
<div fxLayout="row" fxLayoutAlign="space-between center">
<p mat-dialog-title class="!mb-4 !font-bold !text-[28px]">
Manage User Roles
</p>
<button mat-icon-button mat-dialog-close><mat-icon>close</mat-icon></button>
</div>
<div mat-dialog-content>
<div class="mt-4">
<mat-progress-bar mode="indeterminate" *ngIf="isLoadingRoles"></mat-progress-bar>
<!-- Roles Table -->
<table mat-table [dataSource]="dataSource" class="w-full table-auto bg-white dark:bg-night-700">
<!-- Role Name Column -->
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef
class="text-xs uppercase text-gray-400 darfk:text-primary-300 py-3 text-left">
Role
</th>
<td mat-cell *matCellDef="let row" class="darfk:text-white">
{{ row.name }}
</td>
</ng-container>
<!-- Actions Column -->
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef
class="text-xs uppercase text-gray-400 dark:text-primary-300 text-right">
Assign Role
</th>
<td mat-cell *matCellDef="let row" class="dark:text-white">
<div class="relative flex flex-wrap items-center">
<input *ngIf="!loading" (change)="assignOrRevokeRole(row)"
class="relative w-12 h-6 transition-colors appearance-none cursor-pointer hover:ring-blue-400 after:hover:ring-blue-600 checked:hover:bg-blue-600 checked:hover:ring-blue-600 checked:after:hover:ring-blue-600 checked:focus:bg-blue-600 checked:focus:ring-blue-700 checked:after:focus:ring-blue-700 focus-visible:outline-none peer rounded-xl ring-2 ring-inset ring-blue-300 after:absolute after:top-0 after:left-0 after:h-6 after:w-6 after:rounded-full after:bg-white after:ring-2 after:ring-inset after:ring-blue-500 after:transition-all checked:bg-blue-600 checked:after:left-6 checked:after:bg-white checked:ring-blue-500 checked:after:ring-blue-500 disabled:cursor-not-allowed disabled:border-blue-200 disabled:after:ring-blue-300"
type="checkbox" [checked]="roleIsIncluded(row.id)" value="true" id="role" />
</div>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"
class="h-10 hover:bg-gray-100 dark:hover:bg-night-600"></tr>
</table>
</div>
</div>
<div mat-dialog-actions>
<!-- <button mat-flat-button color="primary" type="submit" form="topup-form" class="w-full"><span
*ngIf="!loading">Proceed</span>
<mat-icon *ngIf="loading">
<mat-progress-spinner mode="indeterminate" color="accent" diameter="18"></mat-progress-spinner>
</mat-icon>
</button> -->
</div>
</div>
I want the checbox to be checked in the event that the user already have the role.
I tried checking for the roles the user has and comparing with the all roles and bind with the checkbox. I have also done extensive research to fix the issue to no avail.