109 lines
2.9 KiB
TypeScript
109 lines
2.9 KiB
TypeScript
import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
|
|
import { FormArray, FormBuilder, FormControl, FormGroup } from '@angular/forms';
|
|
import { MatDialog } from '@angular/material/dialog';
|
|
import { ActivatedRoute, Router } from '@angular/router';
|
|
|
|
import { ToasterService } from '../../core/toaster.service';
|
|
import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component';
|
|
import { Role } from '../role';
|
|
import { RoleService } from '../role.service';
|
|
|
|
@Component({
|
|
selector: 'app-role-detail',
|
|
templateUrl: './role-detail.component.html',
|
|
styleUrls: ['./role-detail.component.css'],
|
|
})
|
|
export class RoleDetailComponent implements OnInit, AfterViewInit {
|
|
@ViewChild('nameElement', { static: true }) nameElement?: ElementRef;
|
|
form: FormGroup;
|
|
item: Role = new Role();
|
|
|
|
constructor(
|
|
private route: ActivatedRoute,
|
|
private router: Router,
|
|
private fb: FormBuilder,
|
|
private toaster: ToasterService,
|
|
private dialog: MatDialog,
|
|
private ser: RoleService,
|
|
) {
|
|
// Create form
|
|
this.form = this.fb.group({
|
|
name: '',
|
|
permissions: this.fb.array([]),
|
|
});
|
|
}
|
|
|
|
ngOnInit() {
|
|
this.route.data.subscribe((value) => {
|
|
const data = value as { item: Role };
|
|
this.item = data.item;
|
|
(this.form.get('name') as FormControl).setValue(this.item.name);
|
|
this.form.setControl(
|
|
'permissions',
|
|
this.fb.array(
|
|
this.item.permissions.map((x) =>
|
|
this.fb.group({
|
|
permission: x.enabled,
|
|
}),
|
|
),
|
|
),
|
|
);
|
|
});
|
|
}
|
|
|
|
ngAfterViewInit() {
|
|
setTimeout(() => {
|
|
if (this.nameElement !== undefined) {
|
|
this.nameElement.nativeElement.focus();
|
|
}
|
|
}, 0);
|
|
}
|
|
|
|
save() {
|
|
this.ser.saveOrUpdate(this.getItem()).subscribe(
|
|
() => {
|
|
this.toaster.show('Success', '');
|
|
this.router.navigateByUrl('/roles');
|
|
},
|
|
(error) => {
|
|
this.toaster.show('Error', error);
|
|
},
|
|
);
|
|
}
|
|
|
|
delete() {
|
|
this.ser.delete(this.item.id as string).subscribe(
|
|
() => {
|
|
this.toaster.show('Success', '');
|
|
this.router.navigateByUrl('/roles');
|
|
},
|
|
(error) => {
|
|
this.toaster.show('Error', error);
|
|
},
|
|
);
|
|
}
|
|
|
|
confirmDelete(): void {
|
|
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
|
|
width: '250px',
|
|
data: { title: 'Delete Role?', content: 'Are you sure? This cannot be undone.' },
|
|
});
|
|
|
|
dialogRef.afterClosed().subscribe((result: boolean) => {
|
|
if (result) {
|
|
this.delete();
|
|
}
|
|
});
|
|
}
|
|
|
|
getItem(): Role {
|
|
const formModel = this.form.value;
|
|
this.item.name = formModel.name;
|
|
const array = this.form.get('permissions') as FormArray;
|
|
this.item.permissions.forEach((item, index) => {
|
|
item.enabled = array.controls[index].value.permission;
|
|
});
|
|
return this.item;
|
|
}
|
|
}
|