In this part, we are going to make our Angular 7 Frontend application which will interact with .NET Core web API. Earlier we have made the backend login for crud operation using Web API in Part-1.
If you have not seen the Part-1 then I recommend you to refer that first.
Let’s begin with angular 7 application
Open the Visual Studio Code and open a new terminal from it.
Type the command
ng new crud-frontend
Choose routing to No and use stylesheet as CSS
Now open the newly created angular application from Visual Studio Code
Choose the folder
Open the terminal and type the following commands
ng g c crud-list ng g c crud-operations ng g c crud-view
Navigate to the app folder and create a new folder as shared
create the following new file in the shared folder as crud.model.ts and crud.service.ts
Our whole directory structure will look like this
Install the toaster from the terminal.
npm install ngx-toastr --save
Navigate to the shared folder and open crud.model.ts file and add the code in it.
export class CrudTable { Id: number; Name: string; PhoneNumber: string; Age: string; }
Navigate to the shared folder and open crud.service.ts file and add the code in it.
import { Injectable } from '@angular/core'; import { CrudTable } from './crud.model'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class CrudServices{ public formData:CrudTable = new CrudTable; readonly rootURL = 'http://localhost:59205/api'; list: CrudTable[]; constructor(private http:HttpClient) { } refreshList(){ this.http.get(this.rootURL + '/Crud') .toPromise() .then(res => this.list = res as CrudTable[]); } postDetail() { return this.http.post(this.rootURL + '/Crud', this.formData); } putDetail() { return this.http.put(this.rootURL + '/Crud/'+ this.formData.Id, this.formData); } deleteDetail(id) { return this.http.delete(this.rootURL + '/Crud/'+ id); } }
Here readonly rootURL = ‘http://localhost:59205/api’; is the URL for the web API where 59205 is the port number
Navigate to the crud-list folder and open crud-list.component.html file and add the code in it.
<table class="table table-hover"> <tr *ngFor="let pd of service.list"> <td (click)="populateForm(pd)">{{pd.Name}}</td> <td (click)="populateForm(pd)">{{pd.PhoneNumber}}</td> <td (click)="populateForm(pd)">{{pd.Age}}</td> <td> <i class="far fa-trash-alt fa-lg text-danger" (click)="onDelete(pd.Id)"></i> </td> </tr> </table>
Navigate to the crud-list folder and open crud-list.component.ts file and add the code in it.
import { Component, OnInit } from '@angular/core'; import { CrudTable } from '../shared/crud.model'; import { CrudServices } from '../shared/crud.service'; import { ToastrService } from 'ngx-toastr'; @Component({ selector: 'app-crud-list', templateUrl: './crud-list.component.html', styles: [] }) export class CrudListComponent implements OnInit { constructor(private service: CrudServices, private toastr: ToastrService) { } ngOnInit() { this.service.refreshList(); } populateForm(pd: CrudTable) { this.service.formData = Object.assign({}, pd); } onDelete(Id) { if (confirm('Are you sure to delete this record ?')) { this.service.deleteDetail(Id) .subscribe(res => { this.service.refreshList(); this.toastr.warning('Deleted successfully', 'Detail Deleted Successfully'); }, err => { console.log(err); }) } } }
Navigate to the crud-operations folder and open crud-operations.component.html file and add the code in it.
<form #form="ngForm" autocomplete="off" (submit)="onSubmit(form)"> <input type="hidden" name="Id" [value]="service.Id"> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text bg-white"> <i class="fas fa-user-circle" [class.green-icon]="Name.valid" [class.red-icon]="Name.invalid && Name.touched"></i> </div> </div> <input name="Name" #Name="ngModel" [(ngModel)]="service?.formData.Name" class="form-control" placeholder="Name" required> </div> </div> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text bg-white"> <i class="far fa-credit-card" [class.green-icon]="PhoneNumber.valid" [class.red-icon]="PhoneNumber.invalid && PhoneNumber.touched"></i> </div> </div> <input name="PhoneNumber" #PhoneNumber="ngModel" [(ngModel)]="service.formData.PhoneNumber" class="form-control" placeholder="Phone Number" required maxlength="10" minlength="10"> </div> </div> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <div class="input-group-text bg-white"> <i class="fas fa-calendar-alt" [class.green-icon]="Age.valid" [class.red-icon]="Age.invalid && Age.touched"></i> </div> </div> <input name="Age" #Age="ngModel" [(ngModel)]="service.formData.Age" class="form-control" placeholder="Age" required maxlength="2" minlength="1"> </div> </div> <div class="form-group"> <button class="btn btn-success btn-lg btn-block" type="submit" [disabled]="form.invalid"><i class="fas fa-database"></i> Submit</button> </div> </form>
Navigate to the crud-operations folder and open crud-operations.component.ts file and add the code in it.
import { Component, OnInit } from '@angular/core'; import { NgForm } from '@angular/forms'; import { CrudServices } from '../shared/crud.service'; import { ToastrService } from 'ngx-toastr'; @Component({ selector: 'app-crud-operations', templateUrl: './crud-operations.component.html', styles: [] }) export class CrudOperationsComponent implements OnInit { constructor(private service:CrudServices, private toastr: ToastrService) { } ngOnInit() { } resetForm(form?:NgForm){ if(form!=null) form.resetForm(); this.service.formData = { Id: 0, Name: '', PhoneNumber: '', Age:'' } } onSubmit(form:NgForm){ if (this.service.formData.Id === undefined || this.service.formData.Id==0) this.insertRecord(form); else this.updateRecord(form); } insertRecord(form: NgForm) { this.service.postDetail().subscribe( res => { this.resetForm(form); this.toastr.success('Submitted successfully', 'Detail Added Successfully'); this.service.refreshList(); }, err => { console.log(err); } ) } updateRecord(form: NgForm) { this.service.putDetail().subscribe( res => { this.resetForm(form); this.toastr.info('Submitted successfully', 'Detail Updated Successfully'); this.service.refreshList(); }, err => { console.log(err); } ) } }
Navigate to the crud-view folder and open crud-view.component.html file and add the code in it.
<div class="jumbtron"> <h1 class="display-4 text-center">User Registration</h1> <hr> <div class="row"> <div class="col-md-5"> <app-crud-operations></app-crud-operations> </div> <div class="col-md-7"> <app-crud-list></app-crud-list> </div> </div> </div>
Navigate to the crud-view folder and open crud-view.component.html file and add the code in it.
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-crud-view', templateUrl: './crud-view.component.html', styleUrls: ['./crud-view.component.css'] }) export class CrudViewComponent implements OnInit { constructor() { } ngOnInit() { } }
Open the app.component.html file and add the code
<div class="container"> <app-crud-view></app-crud-view> </div>
Open the app.module.ts file and add the code
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations' import { AppComponent } from './app.component'; import { CrudListComponent } from './crud-list/crud-list.component'; import { CrudOperationsComponent } from './crud-operations/crud-operations.component'; import { CrudViewComponent } from './crud-view/crud-view.component'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { ToastrModule } from 'ngx-toastr'; import { CrudServices } from './shared/crud.service'; @NgModule({ declarations: [ AppComponent, CrudOperationsComponent, CrudListComponent, CrudViewComponent, ], imports: [ BrowserModule, FormsModule, HttpClientModule, BrowserAnimationsModule, ToastrModule.forRoot() ], providers: [CrudServices], bootstrap: [AppComponent] }) export class AppModule { }
Open the index.html file and add the code in it.
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Crud FrontEnd</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"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous"> </head> <body> <app-root></app-root> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html>
Open the style.css file from root folder and add the CSS in it.
/* You can add global styles to this file, and also import other style files */ input.ng-touched.ng-invalid{ border-color: #dc3545; } input.ng-valid{ border-color: #28a745; } .green-icon{ color: #28a745 } .red-icon{ color: #dc3545; } #toast-container > div { opacity: 1; } table tr:hover{ cursor: pointer; }
Now finally open the angular.json file and add the toaster dependency in style tag.
Run the angular 7 project by typing the command.
ng serve
It will compile now and go to localhost:4200 and you will see your frontend application.
Run the project from Visual Studio parallelly and my port number for web API is 59205
Output:
You can download the source code from here.
populateForm(pd: CrudTable) {
this.service.formData = Object.assign({}, pd);
}
when i click the row , the data wont show on form. can you help me ?
I need this operation but not using API ..