barker/bookie/src/app/guest-book/guest-book-list/guest-book-list.component.ts

88 lines
2.8 KiB
TypeScript

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import * as moment from 'moment';
import { BehaviorSubject } from 'rxjs';
import { map } from 'rxjs/operators';
import { ToasterService } from '../../core/toaster.service';
import { ConfirmDialogComponent } from '../../shared/confirm-dialog/confirm-dialog.component';
import { GuestBook } from '../guest-book';
import { GuestBookList } from '../guest-book-list';
import { GuestBookService } from '../guest-book.service';
import { GuestBookListDataSource } from './guest-book-list-datasource';
@Component({
selector: 'app-guest-book-list',
templateUrl: './guest-book-list.component.html',
styleUrls: ['./guest-book-list.component.sass'],
})
export class GuestBookListComponent implements OnInit {
data: BehaviorSubject<GuestBook[]> = new BehaviorSubject<GuestBook[]>([]);
dataSource: GuestBookListDataSource = new GuestBookListDataSource(this.data);
form: FormGroup<{
date: FormControl<Date>;
}>;
/** Columns displayed in the table. Columns IDs can be added, removed, or reordered. */
displayedColumns = ['sno', 'name', 'phone', 'pax', 'date', 'action'];
constructor(
private route: ActivatedRoute,
private router: Router,
private dialog: MatDialog,
private toaster: ToasterService,
private ser: GuestBookService,
) {
// Create form
this.form = new FormGroup({
date: new FormControl(new Date(), { nonNullable: true }),
});
this.listenToDateChange();
}
listenToDateChange(): void {
this.form.controls.date.valueChanges.pipe(map((x) => moment(x).format('DD-MMM-YYYY'))).subscribe((x) =>
this.ser.list(x).subscribe((list: GuestBookList) => {
this.data.next(list.list);
}),
);
}
ngOnInit() {
this.route.data.subscribe((value) => {
const data = value as { list: GuestBookList };
this.data.next(data.list.list);
this.form.setValue({ date: moment(data.list.date, 'DD-MMM-YYYY').toDate() });
});
this.dataSource = new GuestBookListDataSource(this.data);
}
delete(id: string) {
this.ser.delete(id).subscribe(
() => {
this.toaster.show('Success', '');
this.router.navigateByUrl('/guest-book');
},
(error) => {
this.toaster.show('Error', error);
},
);
}
confirmDelete(id: string): void {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
width: '250px',
data: { title: 'Delete Guest Book Entry?', content: 'Are you sure? This cannot be undone.' },
});
dialogRef.afterClosed().subscribe((result: boolean) => {
if (result) {
this.delete(id);
}
});
}
}