Here’s an example of how you can create a simple CRUD application in Angular 15:
- Setting up the project: Use the Angular CLI to create a new Angular 15 project.
Copy codeng new my-crud-app
- Creating a RESTful API: You can use a simple JSON file as a mock API for this example. Create a
db.json
file in thesrc
folder and add some data to it.
Copy code{
"employees": [
{
"id": 1,
"name": "John Doe",
"email": "[email protected]",
"phone": "555-555-5555"
},
{
"id": 2,
"name": "Jane Doe",
"email": "[email protected]",
"phone": "555-555-5555"
}
]
}
- Building the user interface: Create a new component
employees
and generate the following files:employees.component.ts
,employees.component.html
andemployees.component.css
. In theemployees.component.html
file, create a table to display the employees’ data and a button to add a new employee.
Copy code<table>
<tr *ngFor="let employee of employees">
<td>{{employee.name}}</td>
<td>{{employee.email}}</td>
<td>{{employee.phone}}</td>
<td>
<button (click)="editEmployee(employee)">Edit</button>
<button (click)="deleteEmployee(employee)">Delete</button>
</td>
</tr>
</table>
<button (click)="addEmployee()">Add Employee</button>
- Implementing the CRUD logic: In your
employees.component.ts
file, import theHttpClient
module to make HTTP requests. Use thengOnInit
lifecycle hook to fetch the employees’ data from thedb.json
file and store it in a variableemployees
.
Copy codeimport { HttpClient } from '@angular/common/http';
export class EmployeesComponent implements OnInit {
employees: any;
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get('/src/db.json').subscribe(data => {
this.employees = data.employees;
});
}
addEmployee() {
// code to add a new employee
}
editEmployee(employee) {
// code to edit an employee
}
deleteEmployee(employee) {
// code to delete an employee
}
}
- Add the
EmployeesComponent
to theapp.module.ts
file and the routing module to navigate between the different parts of the application.
This is a basic example of how you can create a CRUD application in Angular 15, in a real-world application you need to consider security, data validation, error handling and use a more robust way for storing data.
- Testing and Deployment: Once your application is complete,