95 lines
2.4 KiB
TypeScript
95 lines
2.4 KiB
TypeScript
import { Component, inject, signal } from '@angular/core';
|
|
import { FormsModule } from '@angular/forms';
|
|
import { MailService } from '../../services/mail.service';
|
|
import { Contact } from '../../models/mail.models';
|
|
|
|
@Component({
|
|
selector: 'app-contacts',
|
|
standalone: true,
|
|
imports: [FormsModule],
|
|
providers: [MailService],
|
|
templateUrl: './contacts.component.html',
|
|
styles: ``
|
|
})
|
|
export default class ContactsComponent {
|
|
private mailService = inject(MailService);
|
|
|
|
contacts = signal<Contact[]>([]);
|
|
editingContact = signal<Contact | null>(null);
|
|
|
|
formName = '';
|
|
formEmail = '';
|
|
formPhone = '';
|
|
formCompany = '';
|
|
|
|
constructor() {
|
|
this.loadContacts();
|
|
}
|
|
|
|
loadContacts(): void {
|
|
this.mailService.getContacts().subscribe({
|
|
next: (contacts) => this.contacts.set(contacts),
|
|
error: (e) => console.error('Failed to load contacts', e)
|
|
});
|
|
}
|
|
|
|
saveContact(): void {
|
|
if (!this.formEmail.trim()) return;
|
|
|
|
const contact: Contact = {
|
|
name: this.formName.trim(),
|
|
email: this.formEmail.trim(),
|
|
phone: this.formPhone.trim() || undefined,
|
|
company: this.formCompany.trim() || undefined
|
|
};
|
|
|
|
if (this.editingContact()?.id) {
|
|
this.mailService.updateContact(this.editingContact()!.id!, contact).subscribe({
|
|
next: () => {
|
|
this.resetForm();
|
|
this.loadContacts();
|
|
},
|
|
error: (e) => console.error('Failed to update contact', e)
|
|
});
|
|
} else {
|
|
this.mailService.addContact(contact).subscribe({
|
|
next: () => {
|
|
this.resetForm();
|
|
this.loadContacts();
|
|
},
|
|
error: (e) => console.error('Failed to add contact', e)
|
|
});
|
|
}
|
|
}
|
|
|
|
editContact(contact: Contact): void {
|
|
this.editingContact.set(contact);
|
|
this.formName = contact.name || '';
|
|
this.formEmail = contact.email || '';
|
|
this.formPhone = contact.phone || '';
|
|
this.formCompany = contact.company || '';
|
|
}
|
|
|
|
cancelEdit(): void {
|
|
this.editingContact.set(null);
|
|
this.resetForm();
|
|
}
|
|
|
|
deleteContact(id: number): void {
|
|
if (confirm('Delete this contact?')) {
|
|
this.mailService.deleteContact(id).subscribe({
|
|
next: () => this.loadContacts(),
|
|
error: (e) => console.error('Failed to delete contact', e)
|
|
});
|
|
}
|
|
}
|
|
|
|
resetForm(): void {
|
|
this.formName = '';
|
|
this.formEmail = '';
|
|
this.formPhone = '';
|
|
this.formCompany = '';
|
|
this.editingContact.set(null);
|
|
}
|
|
}
|