// /src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
// Import HttpClientModule
import { HttpClient, HttpClientModule } from '@angular/common/http';
// Import FormsModule for ngModel
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
imports: [
CommonModule,
FormsModule, // Add FormsModule here
HttpClientModule // Add HttpClientModule here
],
standalone: true
})
export class AppComponent implements OnInit {
// Form inputs
title = '';
description = '';
notes: any[] = [];
constructor(private http: HttpClient) { }
ngOnInit(): void {
this.fetchNotes();
}
fetchNotes(): void {
this.http.get<any[]>('http://localhost:5000/notes').subscribe(
(data) => {
this.notes = data;
},
(error) => {
console.error('Error fetching notes:', error);
}
);
}
// Handle form submission
onSubmit(): void {
if (this.title.trim() === '' || this.description.trim() === '') {
alert('Please fill in all fields!');
return;
}
const newNote = {
title: this.title,
description: this.description,
};
this.http.post('http://localhost:5000/notes', newNote).subscribe(
(data) => {
console.log('Data submitted:', data);
// Reset form inputs
this.title = '';
this.description = '';
this.fetchNotes();
},
(error) => {
console.error('Error submitting data:', error);
}
);
}
editNote(note: any): void {
console.log(note)
const newTitle = prompt('Enter new title:', note.title);
const newDescription = prompt('Enter new description:', note.description);
if (newTitle !== null && newDescription !== null) {
const updatedNotes = { ...note, title: newTitle, description: newDescription };
this.http.put(
`http://localhost:5000/notes/${note._id}`, updatedNotes).subscribe(
(data) => {
console.log('Updated note:', data);
this.fetchNotes();
// Refresh the list
},
(error) => {
console.error('Error updating notes:', error);
}
);
}
}
deleteNote(id: number): void {
this.http.delete<any[]>('http://localhost:5000/notes/' + id).subscribe(
(updatedNotes) => {
this.notes = updatedNotes;
},
(error) => {
console.error('Error deleting notes:', error);
}
);
}
}