barker/bookie/src/app/roles/role-detail/role-detail.component.ts

108 lines
2.8 KiB
TypeScript

import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { RoleService } from '../role.service';
import { Role } from '../role';
import { ToasterService } from '../../core/toaster.service';
import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component';
import { MatDialog } from '@angular/material/dialog';
import { FormArray, FormBuilder, FormGroup } from '@angular/forms';
@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;
constructor(
private route: ActivatedRoute,
private router: Router,
private fb: FormBuilder,
private toaster: ToasterService,
private dialog: MatDialog,
private ser: RoleService
) {
this.createForm();
}
createForm() {
this.form = this.fb.group({
name: '',
permissions: this.fb.array([])
});
}
ngOnInit() {
this.route.data
.subscribe((data: { item: Role }) => {
this.item = data.item;
this.form.get('name').setValue(this.item.name);
this.form.setControl('permissions', this.fb.array(
this.item.permissions.map(
x => this.fb.group({
permission: x.enabled
})
)
));
});
}
ngAfterViewInit() {
setTimeout(() => {
this.nameElement.nativeElement.focus();
}, 0);
}
save() {
this.ser.saveOrUpdate(this.getItem())
.subscribe(
(result) => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/roles');
},
(error) => {
this.toaster.show('Danger', error.error);
}
);
}
delete() {
this.ser.delete(this.item.id)
.subscribe(
(result) => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/roles');
},
(error) => {
this.toaster.show('Danger', 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;
}
}