barker/bookie/src/app/taxes/tax-detail/tax-detail.component.ts

104 lines
2.6 KiB
TypeScript

import { AfterViewInit, Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { round } from 'mathjs';
import { Tax } from '../../core/tax';
import { ToasterService } from '../../core/toaster.service';
import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component';
import { TaxService } from '../tax.service';
@Component({
selector: 'app-tax-detail',
templateUrl: './tax-detail.component.html',
styleUrls: ['./tax-detail.component.css'],
})
export class TaxDetailComponent implements OnInit, AfterViewInit {
@ViewChild('nameElement', { static: true }) nameElement?: ElementRef;
form: FormGroup;
item: Tax = new Tax();
constructor(
private route: ActivatedRoute,
private router: Router,
private dialog: MatDialog,
private fb: FormBuilder,
private toaster: ToasterService,
private ser: TaxService,
) {
// Create form
this.form = this.fb.group({
name: '',
rate: '',
});
}
ngOnInit() {
this.route.data.subscribe((value) => {
const data = value as { item: Tax };
this.showItem(data.item);
});
}
showItem(item: Tax) {
this.item = item;
this.form.setValue({
name: this.item.name || '',
rate: this.item.rate * 100,
});
}
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('/taxes');
},
(error) => {
this.toaster.show('Error', error);
},
);
}
delete() {
this.ser.delete(this.item.id as string).subscribe(
() => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/taxes');
},
(error) => {
this.toaster.show('Error', error);
},
);
}
confirmDelete(): void {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '250px',
data: { title: 'Delete Tax?', content: 'Are you sure? This cannot be undone.' },
});
dialogRef.afterClosed().subscribe((result: boolean) => {
if (result) {
this.delete();
}
});
}
getItem(): Tax {
const formModel = this.form.value;
this.item.name = formModel.name;
this.item.rate = round(+formModel.rate / 100, 5);
return this.item;
}
}