BACK 

Angular Application

Angular Application ANGULAR – FRONT-END DEVELOPMENT 1. Angular CLI Installation & Steps 2. Create Angular application 3. Understanding Components, Services, and Modules 4. Creation of Service & Components 5. Install JQuery, Bootstrap 6. Running the Application 1. Angular CLI Installation & Steps C:\ >node -v npm install -g @angular/cli 2. Create Angular Application ng new angular-fronend Note: prompts for routing: type and enter; and prompts for stylesheet: select CSS and enter 3. Understanding Components, Services and Modules Components create-student student-list student-details Services student.service.ts - Service for Http Client methods Modules FormsModule HttpClientModule AppRoutingModule Student Class (Typescript class) student.ts: class Student(id, firstName) 4. Create Service & Components => g – Generate => c – Component => s – Service - ng g s student – ng g c create-student -t -s --skip-tests – ng g c student-details – ng g c student-list – ng g c update-student 5. Install JQuery, Bootstrap npm install bootstrap jquery --save 6. Running Angular Client Application ng serve Open Browser: http://localhost:4200 in an angular.json file: "styles": [ "src/styles.css", "node_modules/bootstrap/dist/css/bootstrap.min.css" ], "scripts": [ "node_modules/jquery/dist/jquery.min.js", "node_modules/bootstrap/dist/js/bootstrap.min.js" ] Note: You can also import bootstrap link in style.css. Create Student Model – right click on src and new file – name it as Student.ts export class Student { id: number; firstName: string; lastName: string; password: string; } tsconfig.json file "strict": false, Create-student component html file: <h3>Create Student</h3> <div [hidden]="submitted" style="width: 400px;"> <form (ngSubmit)="onSubmit()"> <div class="form-group"> <label for="name">First Name</label> <input type="text" class="form-control" id="firstName" required [(ngModel)]="student.firstName" name="firstName"> <label for="lname">Last Name</label> <input type="text" class="form-control" id="lastName" required [(ngModel)]="student.lastName" name="lastName"> <label for="pwd">Password</label> <input type="password" class="form-control" id="password" required [(ngModel)]="student.password" name="password"> </div> <button type="submit" class="btn btn-success">Submit</button> </form> </div> Success message code to be placed as part of create-student component html file: <div [hidden]="!submitted"> <h4>You have submitted successfully!!!</h4> </div> In order to work with two-way binding ngModal – add in app.module import { FormsModule } from '@angular/forms'; and also in imports section FormsModule Properties of create-student component: student: Student = new Student(); submitted = false; Create student component: constructor(private studentService: StudentService, private router: Router) { } onSubmit method to be placed in create student component when form submission: onSubmit() { this.submitted = true; this.save(); } Save method to call: save() { this.studentService .createStudent(this.student).subscribe(data => { console.log(data) this.student = new Student(); //this.gotoList(); this.router.navigate(['/students']); }, error => console.log(error)); } in Student service constructor(private http: HttpClient) { } To work with http - App.module.ts import { HttpClientModule } from '@angular/common/http'; add in imports section also: HttpClientModule createStudent method of student service createStudent(student: Object): Observable<Object> { return this.http.post(`${this.baseUrl}`, student); } Import in service import { HttpClient } from '@angular/common/http'; Path to back-end in student service: private baseUrl = 'http://localhost:8080/api/v1/students'; App.routing.module.ts Change const routes: Routes = []; TO const routes: Routes = [ { path: '', redirectTo: 'student', pathMatch: 'full' }, { path: 'students', component: StudentListComponent }, { path: 'add', component: CreateStudentComponent }, { path: 'details/:id', component: StudentDetailsComponent }, { path: 'update/:id', component: UpdateStudentComponent }, { path: 'update/:id', component: UpdateStudentComponent } ]; App.component.html <nav class="navbar navbar-expand-sm bg-secondary navbar-dark"> <!-- Links --> <ul class="navbar-nav"> <li class="nav-item"> <a routerLink="login" class="nav-link" routerLinkActive="active">Login</a> </li> <li class="nav-item"> <a routerLink="add" class="nav-link" routerLinkActive="active">Add Student</a> </li> <li class="nav-item"> <a routerLink="students" class="nav-link" routerLinkActive="active">Student List</a> </li> </ul> </nav> <div class="container"> <br> <h4 style="text-align: center;">{{title}}</h4> <div class="card"> <div class="card-body"> <router-outlet></router-outlet> </div> </div> </div> Student List Component: which implements onInit students: Observable<Student[]>; Constructor Code: constructor(private studentService: StudentService, private router: Router) {} ngOnInit Code Student List: ngOnInit() { this.reloadData(); } reloadData: reloadData() { this.students = this.studentService.getStudentsList(); } getStudentsList method of Student Service: getStudentsList(): Observable<any> { return this.http.get(`${this.baseUrl}`); } Path to back-end: private baseUrl = 'http://localhost:8080/api/v1/students'; Students property is already declared in StudentsListComponent which implements OnInit export class StudentListComponent implements OnInit{ students: Observable<Student[]>; Display the students property on template of Students List - student list template <table class="table table-hover"> <thead class="bg-light"> <tr> <th>ID</th> <th>FirstName</th> <th>LastName</th> <th>Password</th> <th>Actions</th> </tr> </thead> <tbody> <tr *ngFor="let student of students| async"> <td>{{student.id}}</td> <td>{{student.firstName}}</td> <td>{{student.lastName}}</td> <td>{{student.password}}</td> <td><button (click)="updateStudent(student.id)" class="btn btn-danger">Update</button> <td><button (click)="deleteStudent(student.id)" class="btn btn-danger">Delete</button> <button (click)="studentDetails(student.id)" class="btn btn-info" style="margin-left: 10px">Details</button> </td> </tr> </tbody> </table> studentDetails method in Student List Component Code studentDetails(id: number){ this.router.navigate(['details', id]); } App.routing.module.ts { path: 'details/:id', component: StudentDetailsComponent }, Student Details Component export class StudentDetailsComponent implements OnInit{ properties of Student Details Component id: number; student: Student; constructor of Student Details Component constructor(private route: ActivatedRoute,private router: Router, private studentService: StudentService) { } ngOnInit Code Student Details: ngOnInit() { this.student = new Student(); this.id = this.route.snapshot.params['id']; this.studentService.getStudent(this.id) .subscribe(data => { console.log(data) this.student= data; }, error => console.log(error)); } getStudent method to be placed in service method getStudent(id: number): Observable<any> { return this.http.get(`${this.baseUrl}/${id}`); } Delete Student method to be place in Student List component deleteStudent(id: number) { this.studentService.deleteStudent(id) .subscribe( data => { console.log(data); this.reloadData(); }, error => console.log(error)); } Reload method of Student List Component reloadData() { this.students = this.studentService.getStudentsList(); } Button placed on Student Details Component <button (click)="list()" class="btn btn-primary">Back to Student List</button> List method of Student Details Component list(){ this.router.navigate(['students']); } App.routing.module { path: 'students', component: StudentListComponent }, Various methods of Student Service constructor(private http: HttpClient) { } Getting the student details by id getStudent(id: number): Observable { return this.http.get(`${this.baseUrl}/${id}`); } Updating the student details by id updateStudent(id: number, value: any): Observable<Object>{ return this.http.put(`${this.baseUrl}/${id}`, value); } Deleting the student details by id deleteStudent(id: number): Observable<any> { return this.http.delete(`${this.baseUrl}/${id}`, { responseType: 'text' }); } App.routing.module const routes: Routes = [ { path: '', redirectTo: 'student', pathMatch: 'full' }, { path: 'students', component: StudentListComponent }, { path: 'add', component: CreateStudentComponent }, { path: 'details/:id', component: StudentDetailsComponent }, { path: 'update/:id', component: UpdateStudentComponent }, { path: 'update/:id', component: UpdateStudentComponent } ]; Update student component which implements OnInit export class UpdateStudentComponent implements OnInit{ import import { Component, OnInit } from '@angular/core'; Properties of update student component id: number; student: Student; submitted=false; Constructor of update student component constructor(private route: ActivatedRoute,private router: Router, private studentService: StudentService) { } ngOnInit method ngOnInit() { this.student = new Student(); this.id = this.route.snapshot.params['id']; //calling the service getStudent method by passing the id and subscribing this.studentService.getStudent(this.id) .subscribe(data => { console.log(data) this.student = data; }, error => console.log(error)); } Update method of update student component updateStudent() { //calling the service update student method by passing id, student property and subscribing this.studentService.updateStudent(this.id, this.student) .subscribe(data => { console.log(data); this.student = new Student(); this.gotoList(); }, error => console.log(error)); } // update student component html – template file <h3>Update Student</h3> <div [hidden]="submitted" style="width: 400px;"> <form (ngSubmit)="onSubmit()"> <div class="form-group"> <label for="name">First Name</label> <input type=“text” class=“form-control” id="firstName" required [(ngModel)]="student.firstName" name="firstName"> </div> <button type="submit" class="btn btn-success">Submit</button> </form> </div> //Onsubmit method when form submitted onSubmit() { this.updateStudent(); } //navingating to display students list component with routing gotoList() { this.router.navigate(['/students']); } Proxy Setting: in case of CORS Error Create proxy.conf.mjs in src folder and paste the following. export default [ { "/api/v1": { "target": "http://localhost:8080", "secure": false, "bypass": function (req, res, proxyOptions) { if (req.headers.accept.includes('html')) { console.log('Skipping proxy for browser request.'); return '/index.html'; } req.headers['X-Custom-Header'] = 'yes'; } } } ]; Open angular.json file: paste the code - “proxyConfig”: “src/proxy.conf.mjs” after browserTarget with comma separated. "serve": { "builder": "@angular-devkit/build-angular:dev-server", "configurations": { "production": { "browserTarget": "Angular-Frontend:build:production" }, "development": { "browserTarget": "Angular-Frontend:build:development", "proxyConfig": "src/proxy.conf.mjs" } Code of CrossOrigin of back-end @CrossOrigin(origins = "http://localhost:4200") @RestController @RequestMapping("/api/v1") Code of Service in front-end private baseUrl = 'http://localhost:8080/api/v1/students'; constructor(private http: HttpClient) { } createStudent(student: Object): Observable<Object> { return this.http.post(`${this.baseUrl}`, student); } BACK