Click to setup Angular environment
This demo is based on Reactive Form (RF). 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 ReactiveFormsModule 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 CRUDReactiveForm => 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 CRUDReactiveForm from path D:\AngularDemo\CRUDReactiveForm
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: -
- ngx-toastr setup done. In upcoming step, we use the ngx-toastr.
- In this demo, we are using the reactive form. For that import ReactiveFormsModule in app.module.ts file.
import { ReactiveFormsModule } 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 { FormGroup } from "@angular/forms";
@Injectable()
export class StudentService {
//To Bind Student form data
public studentForm: FormGroup;
//To Fill Gender Dropdown
public genders = ["Male", "Female", "Other"];
//To Store/Get/Delete data from array
public studentList = [];
constructor() {}
Insert(student: Student) {
this.studentList.push(student);
}
Update(student: Student) {
this.studentList[student.Id] = student;
}
Get() {
this.studentList;
}
Delete(indx: number) {
this.studentList.splice(indx, 1);
}
}
Step 20: - Open app.component.ts file => Copy Past following in app.component.ts file
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'CRUD Reactive 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 { Component, OnInit } from "@angular/core";
import { StudentService } from "../student.service";
import { FormGroup, FormBuilder, Validators } from "@angular/forms";
import { ToastrService } from "ngx-toastr";
import { Student } from "../student";
@Component({
selector: "app-student",
templateUrl: "./student.component.html",
styleUrls: ["./student.component.css"]
})
export class StudentComponent implements OnInit {
//This property used for reset the form
public student: Student = {
Id: null,
Name: "",
DOB: null,
Gender: ""
};
constructor(
public service: StudentService,
private toast: ToastrService,
private formBuilder: FormBuilder
) {}
ngOnInit() {
this.ResetForm();
}
// get formControls() { return this.studentForm.controls; }
get name() {
return this.service.studentForm.get("Name");
}
get dob() {
return this.service.studentForm.get("DOB");
}
get gender() {
return this.service.studentForm.get("Gender");
}
ResetForm(studentForm?: FormGroup) {
if (this.service.studentForm != null) {
this.service.studentForm.reset(this.student);
}
this.service.studentForm = this.formBuilder.group({
Id: [null],
Name: ["", [Validators.required, Validators.minLength(3)]],
DOB: ["", Validators.required],
Gender: ["", Validators.required]
});
}
submitForm() {
if (this.service.studentForm.value.Id == null) {
this.InsertForm(this.service.studentForm.value);
} else {
this.updateForm(this.service.studentForm.value);
}
}
InsertForm(student: Student) {
this.service.Insert(student);
this.toast.success("Inserted Successfully.", "Success!");
this.ResetForm();
}
updateForm(student: Student) {
this.service.Update(student);
this.toast.warning("Updated Successfully.", "Success!");
this.ResetForm();
}
}
Step 23: - Open student.component.html file => Copy Past following in student.component.html file
<div class="container">
<form [formGroup]="service.studentForm" (ngSubmit)="submitForm()">
<input type="hidden" formControlName="Id">
<div class="form-group">
<input formControlName="Name" class="form-control" placeholder="Enter Name">
<div *ngIf="name.invalid && name.touched" class="validation-error">
<div *ngIf="name.errors.required">Name is required.</div>
<div *ngIf="name.errors.minlength">Name must be at least 3 characters long.</div>
</div>
</div>
<div class="form-group">
<input type="date" formControlName="DOB" class="form-control" placeholder="Enter DOB">
<div *ngIf="dob.invalid && dob.touched" class="validation-error">DOB is required.</div>
</div>
<div class="form-group">
<select formControlName="Gender" class="form-control">
<option value=''>Select Gender</option>
<option *ngFor="let gender of service.genders" [value]="gender">
{{gender}}
</option>
</select>
<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]="!service.studentForm.valid"></div>
</form>
</div>
Step 24: - Open student-list.component.ts file => Copy Past following in student-list.component.ts file
import { Component, OnInit } from "@angular/core";
import { StudentService } from "../student.service";
import { Student } from "../student";
import { ToastrService } from "ngx-toastr";
@Component({
selector: "app-student-list",
templateUrl: "./student-list.component.html",
styleUrls: ["./student-list.component.css"]
})
export class StudentListComponent implements OnInit {
constructor(public service: StudentService, public toast: ToastrService) {}
ngOnInit() {
this.GetStudentList();
}
GetStudentList() {
this.service.Get();
}
EditForm(student: Student, indx: number) {
//Setting Row Index in student.Id property
student.Id = indx;
this.service.studentForm.setValue({
Id: student.Id,
Name: student.Name,
DOB: student.DOB,
Gender: student.Gender
});
}
DeleteRecord(indx: number) {
if (confirm("Are you sure to delete.")) {
this.service.Delete(indx);
this.toast.warning("Deleted Successfully.", "Success!");
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.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>CRUDReactiveForm</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