Monday 1 June 2020

Angular CRUD example

Click to setup Angular environment

This demo is based on Template Driven Form (TDF). In this we will perform a simple CRUD operation on the memory object. In the latter, we will do the same with database.

Key Features Point: -

1. Student Component

2. Student List Component

3. Student Service

4. Student Class

To Do: -

1. Attach Student & Student List selector in the app.component.html.

2. Import StudentService in the app.module.ts.

3. Import FormsModule in the app.module.ts.

4. Import BrowserAnimationsModule in the app.module.ts.

5. Show messages alert, install the ngx-toastr service.

6. After installing ngx-toastr service, Import ToastrModule in the app.module.ts.

7. Register toastr.css in the angular.json, inside the styles attributes.

8. Use to bootstrap features, register the bootstrap CDN in the index.html.


Lets Start the Project


Step 1: - Create “AngularDemo” folder in the D drive

Step 2: - Open Visual Studio Code

Step 3: - Go to File => Click on Open Folder… => Browse and select created folder “AngularDemo” in the D drive

Step 4: - Type ng new CRUDTemplateDrivenForm => Press Enter


Step 5: - ? Would you like to add Angular routing? (y/N) => Type N => Press Enter


Step 6: - ? Which stylesheet format would you like to use? (Use arrow keys) => Select CSS => Press Enter



Note: - Project created

Step 7: - Go to File => Click on Open Folder… => Browse and select created Project CRUDTemplateDrivenForm from path D:\AngularDemo\CRUDTemplateDrivenForm


Step 8: -Project Loaded in Visual Studio Code


Step 9: - Open Terminal => Go to Terminal => Click on New Terminal



Install “ngx-toaster” package

URL: -https://www.npmjs.com/package/ngx-toastr

Step 10: - Type npm install ngx-toastr --save => Press Enter



Step 11: - Type npm install @angular/animations –-save => Press Enter

Note: -

In latest version angular @angular/animations is default installed, in that case no need to do this step. For verifying the same open package.json file and check dependencies tag.


Step 12: - Open angular.json file and add "node_modules/ngx-toastr/toastr.css" in the styles tag


Step 13: - Open app.module.ts file => Import ToastrModule and BrowserAnimationsModule

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ToastrModule } from 'ngx-toastr';

Note: -

  1. ngx-toastr setup done. In upcoming step, we use the ngx-toastr. 
  2. In this demo, we are using the template driven form. For that import FormsModule in app.module.ts file.
import { FormsModule } from '@angular/forms';


Step 14: - Add Student component => Type ng g c Student => Press Enter


Step 15: - Add StudentList component => Type ng g c StudentList => Press Enter


Step 16: - Add Student service => Type ng g s Student => Press Enter


Step 17: - Add Student class => Type ng g cl Student => Press Enter


Step 18: - Open student.ts file => Copy Past following in student.ts file

export class Student {
    public Id : number;
    public Name : string;
    public DOB : Date;
    public Gender : string;
}


Step 19: - Open student.service.ts file => Copy Past following in student.service.ts file

import { Injectable } from '@angular/core';
import { Student } from './student';
import { NgForm } from '@angular/forms';

@Injectable({
  providedIn: 'root'
})
export class StudentService {
  //To Bind Student form data 
  public studentDataStudent;
  //To Fill Gender Dropdown
  public genderData = ["Male""Female""Other"];
  //To Store/Get/Delete data from array
  public studentList = [];

  constructor() {}

  Insert(studentFormNgForm) {
    this.studentList.push(studentForm.value);
  }

  Update(studentFormNgForm) {
    this.studentList[studentForm.value.Id] = studentForm.value;
  }

  Get() {
    this.studentList;
  }

  Delete(indxnumber) {
    this.studentList.splice(indx1);
  }
}


Step 20: - Open app.component.ts file => Copy Past following in app.component.ts file

import { ComponentVERSION } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'CRUD Template Driven Form-Angular ' + VERSION.major;
}

Step 21: - Open app.component.html file => Clear default code => Copy Past following in app.component.html file

<div class="container">
    <h1>Hello {{name}}!</h1>
</div>
<app-student></app-student>
<hr>
<app-student-list></app-student-list>

Step 22: - Open student.component.ts file => Copy Past following in student.component.ts file

import { ComponentOnInit } from "@angular/core";
import { StudentService } from "../student.service";
import { ToastrService } from 'ngx-toastr';
import { NgForm } from "@angular/forms";

@Component({
  selector: "app-student",
  templateUrl: "./student.component.html",
  styleUrls: ["./student.component.css"]
})
export class StudentComponent implements OnInit {

  constructor(public serviceStudentServiceprivate toastrToastrService) {}

  ngOnInit() {
    this.ResetForm();
  }

  ResetForm(studentForm?: NgForm) {
    if (studentForm != nullstudentForm.resetForm();
    this.service.studentData = {
      Id: null,
      Name: "",
      DOB: null,
      Gender: ""
    };
  }

  submitForm(studentFormNgForm) {
    if (studentForm.value.Id == null) {
      this.InsertForm(studentForm);
    } else {
      this.updateForm(studentForm);
    }
  }

  InsertForm(studentFormNgForm) {
    this.service.Insert(studentForm);
    this.toastr.success('Inserted Successfully.''Message!');
    this.ResetForm(studentForm);
  }

  updateForm(studentFormNgForm) {
    this.service.Update(studentForm);
    this.toastr.warning('Updated Successfully.''Message!');
    this.ResetForm(studentForm);
  }
}

Step 23: - Open student.component.html file => Copy Past following in student.component.html file

<div class="container">
    <form #studentForm="ngForm" (ngSubmit)="submitForm(studentForm)" autocomplete="off">
        <input type="hidden" name="Id" #Id="ngModel" [(ngModel)]="service.studentData.Id">
        <div class="form-group">
            <input name="Name" #Name="ngModel" class="form-control" [(ngModel)]="service.studentData.Name" placeholder="Enter Name" required>
            <!-- <div [hidden]="Name.valid || Name.pristine" class="alert alert-danger"> Name is required</div> -->
            <div *ngIf="Name.invalid && Name.touched" class="validation-error"> Name is required</div>
        </div>
        <div class="form-group">
            <input type="date" name="DOB" #DOB="ngModel" class="form-control" [(ngModel)]="service.studentData.DOB" required>
            <!-- <div [hidden]="DOB.valid || DOB.pristine" class="alert alert-danger"> DOB is required</div> -->
            <div *ngIf="DOB.invalid && DOB.touched" class="validation-error">DOB is required</div>
        </div>
        <div class="form-group">
            <select name="Gender" #Gender="ngModel" class="form-control" [(ngModel)]="service.studentData.Gender" required>
          <option value="">Select Gender</option>
          <option *ngFor="let gender of service.genderData" [value]="gender">
            {{gender}}
          </option>
        </select>
            <!-- <div [hidden]="Gender.valid || Gender.pristine" class="alert alert-danger"> Gender is required</div> -->
            <div *ngIf="Gender.invalid && Gender.touched" class="validation-error"> Gender is required</div>
        </div>
        <div class="form-group">
            <input type="submit" class="btn btn-primary btn-lg btn-block" [disabled]="!studentForm.form.valid">
      </div>
    </form>
</div>

Step 24: - Open student-list.component.ts file => Copy Past following in student-list.component.ts file

import { ComponentOnInit } from "@angular/core";
import { StudentService } from "../student.service";
import { ToastrService } from 'ngx-toastr';
import { Student } from "../student";

@Component({
  selector: "app-student-list",
  templateUrl: "./student-list.component.html",
  styleUrls: ["./student-list.component.css"]
})
export class StudentListComponent implements OnInit {

  constructor(public serviceStudentServiceprivate toastrToastrService) {}

  ngOnInit() {
    this.GetStudentList();
  }

  GetStudentList() {
    this.service.Get();
  }

  EditForm(studentStudentindxnumber) {
    //Setting Row Index in student.Id property
    student.Id = indx;
    //Creating a copy of student and setting student data to this.service.studentData property
    this.service.studentData = Object.assign({}, student);
  }

  DeleteRecord(indx : number) {
    this.service.Delete(indx);
    this.toastr.warning('Deleted Successfully.''Message!');
    this.GetStudentList();
  }
}

Step 25: - Open student-list.component.html file => Copy Past following in student-list.component.html file

<div class="container" *ngIf="service.studentList.length">
    <table class="table table-bordered">
        <thead class="thead-dark">
            <tr>
                <th scope="col">SrNo</th>
                <th scope="col">Name</th>
                <th scope="col">DOB</th>
                <th scope="col">Gender</th>
                <th scope="col" class="text-center" colspan="2">Action</th>
            </tr>
        </thead>
        <tbody>
            <tr scope="row" *ngFor="let student of service.studentList;let indx = index">
                <td>{{indx+1}}</td>
                <td>{{student.Name}}</td>
                <td>{{student.DOB}}</td>
                <td>{{student.Gender}}</td>
                <td class="text-center">
                    <button (click)="EditForm(student,indx)" class="btn btn-sm btn-outline-info">Edit</button></td>
                <td class="text-center">
                    <button (click)="DeleteRecord(indx)" class="btn btn-sm btn-outline-danger">Delete</button></td>
            </tr>
        </tbody>
    </table>
</div>

Step 26: - Open Root styles.css file => Copy Past following in Root styles.css file

/* You can add global styles to this file, and also import other style files */
input.ng-touched.ng-invalid {
    border-color:red;
}
.validation-error {
    color : red;
}

Step 27: - Open app.module.ts file and import and register the StudentService in Providers tag

import { StudentService } from './student.service';

@NgModule({
  declarations: [
  ],
  imports: [
  ],
  providers: [StudentService],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 28: - To use bootstrap => Open index.html file and add bootstrap CDN link in html head tag.

URL: - https://getbootstrap.com/docs/4.3/getting-started/introduction/

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>CRUDTemplateDrivenForm</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
  <app-root></app-root>
</body>
</html>

Step 29: - Open Terminal => Type ng serve --o => Press Enter

Add Done

Output



No comments:

Post a Comment