barker/bookie/src/app/printers/printer-detail/printer-detail.component.ts

109 lines
2.7 KiB
TypeScript

import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { MatDialog } from "@angular/material/dialog";
import { PrinterService } from '../printer.service';
import { Printer } from '../../core/printer';
import { ToasterService } from '../../core/toaster.service';
import { ConfirmDialogComponent } from "../../shared/confirm-dialog/confirm-dialog.component";
@Component({
selector: 'app-printer-detail',
templateUrl: './printer-detail.component.html',
styleUrls: ['./printer-detail.component.css']
})
export class PrinterDetailComponent implements OnInit, AfterViewInit {
@ViewChild('nameElement', { static: true }) nameElement: ElementRef;
form: FormGroup;
item: Printer;
constructor(
private route: ActivatedRoute,
private router: Router,
private dialog: MatDialog,
private fb: FormBuilder,
private toaster: ToasterService,
private ser: PrinterService
) {
this.createForm();
}
createForm() {
this.form = this.fb.group({
name: '',
address: '',
cutCode: ''
});
}
ngOnInit() {
this.route.data
.subscribe((data: { item: Printer }) => {
this.showItem(data.item);
});
}
showItem(item: Printer) {
this.item = item;
this.form.setValue({
name: this.item.name || '',
address: this.item.address || '',
cutCode: this.item.cutCode || ''
});
}
ngAfterViewInit() {
setTimeout(() => {
this.nameElement.nativeElement.focus();
}, 0);
}
save() {
this.ser.saveOrUpdate(this.getItem())
.subscribe(
(result) => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/printers');
},
(error) => {
this.toaster.show('Danger', error.error);
}
);
}
delete() {
this.ser.delete(this.item.id)
.subscribe(
(result) => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/printers');
},
(error) => {
this.toaster.show('Danger', error.error);
}
);
}
confirmDelete(): void {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '250px',
data: {title: 'Delete Printer?', content: 'Are you sure? This cannot be undone.'}
});
dialogRef.afterClosed().subscribe((result: boolean) => {
if (result) {
this.delete();
}
});
}
getItem(): Printer {
const formModel = this.form.value;
this.item.name = formModel.name;
this.item.address = formModel.address;
this.item.cutCode = formModel.cutCode;
return this.item;
}
}