Hello friends, welcome back to my blog. Today in this blog post, I am going to tell you, Angular 11 Crud Tutorial with Service.
Angular 11 came and if you are new then you must check below link:
Friends now I proceed onwards and here is the working code snippet for Angular 11 Crud Tutorial with Service and please use carefully this to avoid the mistakes:
1. Firstly friends we need fresh angular 11 setup and for this we need to run below commands but if you already have angular 11 setup then you can avoid below commands. Secondly we should also have latest node version installed on our system:
npm install -g @angular/cli ng new angularcrud //Create new Angular Project cd angularcrud // Go inside the Angular Project Folder ng serve --open // Run and Open the Angular Project http://localhost:4200/ // Working Angular Project Url
2. Now friends, here we need to run below commands into our project terminal to install datatable modules, bootstrap(for good looks), jquery, sweetalert modules into our angular application:
npm install jquery --save npm install datatables.net --save npm install datatables.net-dt --save npm install angular-datatables --save npm install @types/jquery --save-dev npm install @types/datatables.net --save-dev npm install --save sweetalert2 npm install bootstrap --save
3. After done with commands add below code into you angular.json file:
"styles": [ ... "src/styles.css", "node_modules/datatables.net-dt/css/jquery.dataTables.css", "node_modules/bootstrap/dist/css/bootstrap.min.css", "node_modules/sweetalert2/src/sweetalert2.scss" ], "scripts": [ ... "node_modules/jquery/dist/jquery.js", "node_modules/datatables.net/js/jquery.dataTables.js", "node_modules/bootstrap/dist/js/bootstrap.js", "node_modules/sweetalert2/dist/sweetalert2.js" ]
4. Now friends, we need to run below commands to create service file and run our angular project:
ng g service crud ng serve --o
5. Now friends we just need to add below code into src/app/app.module.ts file:
... import { ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; ... imports: [ ... ReactiveFormsModule HttpClientModule ]
6. Now friends we just need to add below code into src/app/crud.service.ts file:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class CrudService { userData:any; userid:any; singleuserdata:any; constructor(private http:HttpClient) { } //get all users details public getusers() { return this.http.get('http://localhost/users.php'); } //add new user public adduser(userData) { return this.http.post('http://localhost/users.php/' , userData).subscribe((res: Response) => {}); } //get single user public getsingleuser(userid) { return this.http.post('http://localhost/users.php/' , userid).subscribe((res: Response) => { this.singleuserdata = res[0]; }); } //delete user public deleteuser(userid) { return this.http.post('http://localhost/users.php/' , userid).subscribe((res: Response) => {}); } //update user public updateuser(userid) { return this.http.post('http://localhost/users.php/' , userid).subscribe((res: Response) => {}); } }
7. Now friends we just need to add below code into src/app/app.component.ts file:
import { Component } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import Swal from 'sweetalert2/dist/sweetalert2.js'; import { CrudService } from './crud.service'; declare let $: any; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { constructor(private crudservice: CrudService, private formBuilder: FormBuilder) {} data = []; userdata:any //Add Form addForm: FormGroup; submitted = false; get f() { return this.addForm.controls; } onSubmit() { this.submitted = true; // stop here if form is invalid if (this.addForm.invalid) { return; } if(this.submitted) { // Initialize Params Object var myFormData = new FormData(); // Begin assigning parameters myFormData.append('myUsername', this.addForm.value.firstname); myFormData.append('myEmail', this.addForm.value.email); this.crudservice.adduser(myFormData); this.crudservice.getusers().subscribe((ret: any[])=>{ this.data = ret; $("#addUser").modal("hide"); //sweetalert message popup Swal.fire({ title: 'Hurray!!', text: "User has been added successfully", icon: 'success' }); $('#datatableexample').DataTable().destroy(); this.crudservice.getusers().subscribe((ret: any[])=>{ this.data = ret; setTimeout(()=>{ $('#datatableexample').DataTable( { pagingType: 'full_numbers', pageLength: 5, processing: true, lengthMenu : [5, 10, 25], order:[0,"desc"] } ); }, 500); }); }); } } ngOnInit() { //Add form validations this.addForm = this.formBuilder.group({ email: ['', [Validators.required, Validators.email]], firstname: ['', [Validators.required]] }); //Get all usera details this.crudservice.getusers().subscribe((ret: any[])=>{ this.data = ret; setTimeout(()=>{ $('#datatableexample').DataTable( { pagingType: 'full_numbers', pageLength: 5, processing: true, lengthMenu : [5, 10, 25], order:[0,"desc"] } ); }, 100); }); //Edit form validations this.editForm = this.formBuilder.group({ email: ['', [Validators.required, Validators.email]], firstname: ['', [Validators.required]] }); } //Add New User Function addnewuser() { $("#addUser").modal("show"); } //View User //For modal popup hiding first time showuser = false; openuser(id) { // Initialize Params Object var myFormData = new FormData(); // Begin assigning parameters myFormData.append('userid', id); //user details post request this.crudservice.getsingleuser(myFormData); setTimeout(()=>{ this.userdata = this.crudservice.singleuserdata; this.showuser = true; }, 500); setTimeout(()=>{ $("#showuser").modal("show"); }, 800); } //Delete User deleteuser(id) { // Initialize Params Object var myFormData = new FormData(); // Begin assigning parameters myFormData.append('deleteid', id); this.crudservice.deleteuser(myFormData); //sweetalert message popup Swal.fire({ title: 'Hurray!!', text: "User has been deleted successfully", icon: 'success' }); $('#datatableexample').DataTable().destroy(); this.crudservice.getusers().subscribe((ret: any[])=>{ this.data = ret; setTimeout(()=>{ $('#datatableexample').DataTable( { pagingType: 'full_numbers', pageLength: 5, processing: true, lengthMenu : [5, 10, 25], order:[0,"desc"] } ); }, 500); }); } //Edit User code starts get fe() { return this.editForm.controls; } onSubmitEdit() { this.submitted = true; // stop here if form is invalid if (this.editForm.invalid) { return; } //True if all the fields are filled if(this.submitted) { // Initialize Params Object var myFormData = new FormData(); // Begin assigning parameters myFormData.append('updateUsername', this.editForm.value.firstname); myFormData.append('updateEmail', this.editForm.value.email); myFormData.append('updateid', this.userID); this.crudservice.updateuser(myFormData); //sweetalert message popup $("#editModal").modal("hide"); Swal.fire({ title: 'Hurray!!', text: "User has been updated successfully", icon: 'success' }); $('#datatableexample').DataTable().destroy(); this.crudservice.getusers().subscribe((ret: any[])=>{ this.data = ret; setTimeout(()=>{ $('#datatableexample').DataTable( { pagingType: 'full_numbers', pageLength: 5, processing: true, lengthMenu : [5, 10, 25], order:[0,"desc"] } ); }, 500); }); } } showedituser = false; editForm: FormGroup; userID:any; edituser(id) { // Initialize Params Object var myFormData = new FormData(); // Begin assigning parameters myFormData.append('userid', id); //user details post request this.crudservice.getsingleuser(myFormData); setTimeout(()=>{ this.userdata = this.crudservice.singleuserdata; this.editForm.controls["firstname"].setValue(this.userdata.username); this.editForm.controls["email"].setValue(this.userdata.email); this.userID = this.userdata.id; this.showedituser = true; }, 500); setTimeout(()=>{ $("#editModal").modal("show"); }, 800); // Initialize Params Object var myFormData = new FormData(); // Begin assigning parameters myFormData.append('userid', id); } }
8. Now friends we just need to add below code into src/app/app.component.html file to see the output on browser:
<h1>therichpost.com</h1> <div class="container mt-5 mb-5"> <!--Add User Button--> <button class="btn btn-primary mb-5" (click)="addnewuser()">Add New User</button> <!--Datatable with User Details--> <table class="table table-hover table-bordered" id="datatableexample"> <thead> <tr> <th>ID</th> <th>Email</th> <th>Username</th> <th>Actions</th> </tr> </thead> <tbody> <tr *ngFor="let group of data"> <td>{{group.id}}</td> <td>{{group.email}}</td> <td>{{group.username}}</td> <td> <button class="bg-info" (click)="openuser(group.id)"> <i class="fas fa-eye"></i> </button> <button class="bg-warning" (click)="edituser(group.id)"> <i class="fas fa-edit"></i> </button> <button class="bg-danger" (click)="deleteuser(group.id)"> <i class="fas fa-trash"></i> </button> </td> </tr> </tbody> </table> </div> <!--Add User Modal--> <div class="modal" id="addUser"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title align-center">Add User Details</h4> <button type="button" class="close" data-dismiss="modal">×</button> </div> <div class="modal-body"> <form [formGroup]="addForm" (ngSubmit)="onSubmit()"> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label>Username</label> <input type="text" formControlName="firstname" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstname.errors }" /> <div *ngIf="submitted && f.firstname.errors" class="invalid-feedback"> <div *ngIf="f.firstname.errors.required">Name is required</div> </div> </div> </div> <div class="col-sm-6"> <div class="form-group"> <label>Email</label> <input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" /> <div *ngIf="submitted && f.email.errors" class="invalid-feedback"> <div *ngIf="f.email.errors.required">Email is required</div> <div *ngIf="f.email.errors.email">Email must be a valid email address</div> </div> </div> </div> </div> <button type="submit" class="btn btn-primary">Add</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!--View User Details--> <div class="modal" id="showuser" *ngIf="showuser"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title align-center">User : {{userdata.username}}</h4> <button type="button" class="close" data-dismiss="modal">×</button> </div> <div class="modal-body text-center"> <table class="table table-hover table-bordered"> <thead> <tr> <th>ID</th> <th>Email</th> <th>Username</th> </tr> </thead> <tbody> <!-- User Dynamic data--> <tr> <td>{{userdata.id}}</td> <td>{{userdata.email}}</td> <td>{{userdata.username}}</td> </tr> </tbody> </table> </div> </div> </div> </div> <!--Edit User--> <div class="modal" id="editModal" *ngIf="showedituser"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title align-center">Edit : {{userdata.username}}</h4> <button type="button" class="close" data-dismiss="modal">×</button> </div> <div class="modal-body"> <form [formGroup]="editForm" (ngSubmit)="onSubmitEdit()"> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label>Username</label> <input type="text" formControlName="firstname" class="form-control" [ngClass]="{ 'is-invalid': submitted && fe.firstname.errors }" /> <div *ngIf="submitted && fe.firstname.errors" class="invalid-feedback"> <div *ngIf="fe.firstname.errors.required">Name is required</div> </div> </div> </div> <div class="col-sm-6"> <div class="form-group"> <label>Email</label> <input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && fe.email.errors }" /> <div *ngIf="submitted && fe.email.errors" class="invalid-feedback"> <div *ngIf="fe.email.errors.required">Email is required</div> <div *ngIf="fe.email.errors.email">Email must be a valid email address</div> </div> </div> </div> </div> <button type="submit" class="btn btn-primary">Update</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button> </div> </div> </div> </div>
9. Now friends, we have to add some code into our src/index.html file for font icons:
<head> ... <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css"> <style> .fa-eye:before{color: #fff;} </style> </head>
10. Now friends here is my php code snippet to fetch and save data and show into angular 11 and I added this code into my xampp/htdocs/users.php file:
//Please create users database inside phpmysql admin and create userdetails tabel and create id, email and username fields:
<?php //Please create users database inside phpmysql admin and create userdetails tabel and create id, email and username fields $servername = "localhost"; $username = "root"; $password = ""; $dbname = "users"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } //Add user if(isset($_POST['myEmail'])) { $sql = "INSERT INTO userdetails (email, username) VALUES ('".$_POST['myEmail']."', '".$_POST['myUsername']."')"; if (mysqli_query($conn,$sql)) { $data = array("data" => "You Data added successfully"); echo json_encode($data); } else { $data = array("data" => "Error: " . $sql . "<br>" . $conn->error); echo json_encode($data); } } //Get single user details elseif(isset($_POST['userid'])) { $trp = mysqli_query($conn, "SELECT * from userdetails where id =".$_POST['userid']); $rows = array(); while($r = mysqli_fetch_assoc($trp)) { $rows[] = $r; } print json_encode($rows); } //Delete user elseif(isset($_POST['deleteid'])) { $sql = mysqli_query($conn, "DELETE from userdetails where id =".$_POST['deleteid']); if ($sql) { $data = array("data" => "Record deleted successfully"); echo json_encode($data); } else { $data = array("data" =>"Error deleting record: " . mysqli_error($conn)); echo json_encode($data); } } //Update user elseif(isset($_POST["updateid"])) { $sql = "UPDATE userdetails SET email='".$_POST["updateEmail"]."', username='".$_POST["updateUsername"]."' WHERE id=".$_POST["updateid"]; if ($conn->query($sql) === TRUE) { $data = array("data" => "Record updated successfully"); echo json_encode($data); } else { $data = array("data" => "Error updating record: " . $conn->error); echo json_encode($data); } } else { //get all users details $trp = mysqli_query($conn, "SELECT * from userdetails ORDER BY id DESC"); $rows = array(); while($r = mysqli_fetch_assoc($trp)) { $rows[] = $r; } print json_encode($rows); } ?>
Now we are done friends. If you have any kind of query or suggestion or any requirement then feel free to comment below.
Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements. For better understanding must watch video above.
I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad.
Jassa
Thanks
Recent Comments