Angular 7 Tutorial - Building CRUD Web Application

Download as pdf or txt
Download as pdf or txt
You are on page 1of 39

27/4/2019 Angular 

7 Tutorial: Building CRUD Web Application

Start Download - View PDF

Ad

Home (/) > Programming Blog (/post-category/595f867edbd39e7571e183dc/programming-blog) > Node.js (/post-sub-


category/58a9196f80aca748640ce352/nodejs)

Angular 7 Tutorial: Building CRUD Web Application


by Didin J. on oct 20, 2018

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 1/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

A comprehensive step by step tutorial on Build CRUD (Create, Read, Update, Delete)
Web Application using the New Angular 7

A comprehensive step by step tutorial on build CRUD (Create, Read, Update, Delete) Web Application using the New Angular 7.
The Angular 7 just released a day ago, it comes with a few new feature and improvements. As usual, we are trying every Angular
released with CRUD (Create, Read, Update, Delete) operation.

We will use a separate backend using Express.js/MongoDB (http://Express.js/MongoDB) and accessing by Angular 7 that run in
the different port. Of course, the Express API server runs with CORS enable. You can download the working Express API server
from here (https://github.com/didinj/NodeRestApi.git) or you can do the same way using your own Backend Frameworks.

Table of Contents:
https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 2/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

Angular 7 Tutorial: Install or Update Angular 7 CLI and Create Application


Angular 7 Tutorial: Create Routes for Navigation between Angular Pages/Component
Angular 7 Tutorial: Create Service for Accessing RESTful API
Angular 7 Tutorial: Display List of Products using Angular Material
Angular 7 Tutorial: Show and Delete Product Details using Angular Material
Angular 7 Tutorial: Add a Product using Angular Material
Angular 7 Tutorial: Edit a Book using Angular Material
Angular 7 Tutorial: Run and Test the Angular 7 CRUD Web Application

The following tools, frameworks, and modules are required for this tutorial:
Node.js (https://nodejs.org/en/) (recommended version)
Angular 7 CLI (https://cli.angular.io/)
Angular 7 (https://angular.io/)
Express and MongoDB API (https://github.com/didinj/NodeRestApi.git)
Terminal (Mac/Linux) or Node Command Line (Windows)
IDE or Text Editor
We assume that you have installed Node.js. Now, we need to check the Node.js and NPM versions. Open the terminal or Node
command line then type this commands.

node ‐v
v8.12.0
npm ‐v
6.4.1

That's the Node.js and NPM version that we are using. Now, you can go to the main steps.

1. Angular 7 Tutorial: Install or Update Angular 7 CLI and Create Application


To install or update Angular 7 CLI, type this command in the Terminal or Node Command Line.

sudo npm install ‐g @angular/cli

Now, you have the latest version of Angular CLI.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 3/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

ng ‐‐version

Angular CLI: 7.0.1
Node: 8.12.0
OS: darwin x64
Angular:
...

Package                      Version
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
@angular‐devkit/architect    0.10.1
@angular‐devkit/core         7.0.1
@angular‐devkit/schematics   7.0.1
@schematics/angular          7.0.1
@schematics/update           0.10.1
rxjs                         6.3.3
typescript                   3.1.3

Next, create a new Angular 7 Web Application using this Angular CLI command.

ng new angular7‐crud

If you get the question like below, choose `Yes` and `SCSS` (or whatever you like to choose).

? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? SCSS

Next, go to the newly created Angular 7 project folder.

cd angular7‐crud

Type this command to run the Angular 7 application using this command.

ng serve

Open your browser then go to this address `localhost:4200`, you should see this Angular 7 page.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 4/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

2. Angular 7 Tutorial: Create Routes for Navigation between Angular


Pages/Component
The Angular 7 routes already added when we create new Angular 7 application in the previous step. Before configure the routes,
type this command to create a new Angular 7 components.

ng g component products
ng g component product‐detail
ng g component product‐add
ng g component product‐edit

Open `src/app/app.module.ts` then you will see those components imported and declared in `@NgModule` declarations. Next,
open and edit `src/app/app-routing.module.ts` then add this imports.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 5/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

import { ProductsComponent } from './products/products.component';
import { ProductDetailComponent } from './product‐detail/product‐detail.component';
import { ProductAddComponent } from './product‐add/product‐add.component';
import { ProductEditComponent } from './product‐edit/product‐edit.component';

Add these arrays to the existing routes constant.

const routes: Routes = [
  {
    path: 'products',
    component: ProductsComponent,
    data: { title: 'List of Products' }
  },
  {
    path: 'product‐details/:id',
    component: ProductDetailComponent,
    data: { title: 'Product Details' }
  },
  {
    path: 'product‐add',
    component: ProductAddComponent,
    data: { title: 'Add Product' }
  },
  {
    path: 'product‐edit/:id',
    component: ProductEditComponent,
    data: { title: 'Edit Product' }
  },
  { path: '',
    redirectTo: '/products',
    pathMatch: 'full'
  }
];

Open and edit `src/app/app.component.html` and you will see existing router outlet. Next, modify this HTML page to fit the
CRUD page.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 6/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

<div style="text‐align:center">
  <img width="150" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA
yNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA
8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0
iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3Z
nPg==">
</div>

<div class="container">
  <router‐outlet></router‐outlet>
</div>

Open and edit `src/app/app.component.scss` then replace all SASS codes with this.

.container {
  padding: 20px;
}

3. Angular 7 Tutorial: Create Service for Accessing RESTful API


Before creating a service for RESTful API access, first, we have to install or register `HttpClientModule`. Open and edit
`src/app/app.module.ts` then add this import.

import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

Add it to `@NgModule` imports after `BrowserModule`.

imports: [
  BrowserModule,
  FormsModule,
  HttpClientModule,
  AppRoutingModule
],

We will use type specifier to get a typed result object. For that, create a new Typescript file `src/app/product.ts` then add this
lines of Typescript codes.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 7/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

export class Product {
  id: number;
  prod_name: string;
  prod_desc: string;
  prod_price: number;
  updated_at: Date;
}

Next, generate an Angular 7 service by typing this command.

ng g service api

Next, open and edit `src/app/api.service.ts` then add this imports.

import { Observable, of, throwError } from 'rxjs';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { catchError, tap, map } from 'rxjs/operators';
import { Product } from './product';

Add these constants before the `@Injectable`.

const httpOptions = {
  headers: new HttpHeaders({'Content‐Type': 'application/json'})
};
const apiUrl = "/api/v1/products";

Inject `HttpClient` module to the constructor.

constructor(private http: HttpClient) { }

Add the error handler function.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 8/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

private handleError<T> (operation = 'operation', result?: T) {
  return (error: any): Observable<T> => {

    // TODO: send the error to remote logging infrastructure
    console.error(error); // log to console instead

    // Let the app keep running by returning an empty result.
    return of(result as T);
  };
}

Add all CRUD (create, read, update, delete) functions of products data.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 9/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

getProducts (): Observable<Product[]> {
  return this.http.get<Product[]>(apiUrl)
    .pipe(
      tap(heroes => console.log('fetched products')),
      catchError(this.handleError('getProducts', []))
    );
}

getProduct(id: number): Observable<Product> {
  const url = `${apiUrl}/${id}`;
  return this.http.get<Product>(url).pipe(
    tap(_ => console.log(`fetched product id=${id}`)),
    catchError(this.handleError<Product>(`getProduct id=${id}`))
  );
}

addProduct (product): Observable<Product> {
  return this.http.post<Product>(apiUrl, product, httpOptions).pipe(
    tap((product: Product) => console.log(`added product w/ id=${product.id}`)),
    catchError(this.handleError<Product>('addProduct'))
  );
}

updateProduct (id, product): Observable<any> {
  const url = `${apiUrl}/${id}`;
  return this.http.put(url, product, httpOptions).pipe(
    tap(_ => console.log(`updated product id=${id}`)),
    catchError(this.handleError<any>('updateProduct'))
  );
}

deleteProduct (id): Observable<Product> {
  const url = `${apiUrl}/${id}`;

  return this.http.delete<Product>(url, httpOptions).pipe(
    tap(_ => console.log(`deleted product id=${id}`)),
    catchError(this.handleError<Product>('deleteProduct'))
  );
}

4. Angular 7 Tutorial: Display List of Products using Angular Material


https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 10/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

We will display the list of products that get via API Service. For that, open and edit `src/app/products/products.component.ts`
then add this imports.

import { ApiService } from '../api.service';

Next, inject the API Service to the constructor.

constructor(private api: ApiService) { }

Next, for user interface (UI) we will use Angular 6 Material and CDK. There's a CLI for generating a Material component like Table
as a component, but we will create or add the Table component from scratch to existing component. Type this command to
install Angular Material.

ng add @angular/material

If there are questions like below, just use the default answer.

? Enter a prebuilt theme name, or "custom" for a custom theme: purple‐green
? Set up HammerJS for gesture recognition? Yes
? Set up browser animations for Angular Material? Yes

We will register all required Angular Material components or modules to `src/app/app.module.ts`. Open and edit that file then
add this imports.

import {
  MatInputModule,
  MatPaginatorModule,
  MatProgressSpinnerModule,
  MatSortModule,
  MatTableModule,
  MatIconModule,
  MatButtonModule,
  MatCardModule,
  MatFormFieldModule } from "@angular/material";

Also, modify `FormsModule` import to add `ReactiveFormsModule`.

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

Register the above modules to `@NgModule` imports.


https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 11/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

imports: [
  BrowserModule,
  FormsModule,
  HttpClientModule,
  AppRoutingModule,
  ReactiveFormsModule,
  BrowserAnimationsModule,
  MatInputModule,
  MatTableModule,
  MatPaginatorModule,
  MatSortModule,
  MatProgressSpinnerModule,
  MatIconModule,
  MatButtonModule,
  MatCardModule,
  MatFormFieldModule
],

Next, back to `src/app/products/products.component.ts` then add this imports.

import { Product } from '../product';

Declare the variables of Angular Material Table Data Source before the constructor.

displayedColumns: string[] = ['prod_name', 'prod_price'];
data: Product[] = [];
isLoadingResults = true;

Modify the `ngOnInit` function to get list of products immediately.

ngOnInit() {
  this.api.getProducts()
    .subscribe(res => {
      this.data = res;
      console.log(this.data);
      this.isLoadingResults = false;
    }, err => {
      console.log(err);
      this.isLoadingResults = false;
    });
}

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 12/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

Next, open and edit `src/app/products/products.component.html` then replace all HTML tags with this Angular Material tags.

<div class="example‐container mat‐elevation‐z8">
  <div class="example‐loading‐shade"
       *ngIf="isLoadingResults">
    <mat‐spinner *ngIf="isLoadingResults"></mat‐spinner>
  </div>
  <div class="button‐row">
    <a mat‐flat‐button color="primary" [routerLink]="['/product‐add']"><mat‐icon>add</mat‐icon></a>
  </div>
  <div class="mat‐elevation‐z8">
    <table mat‐table [dataSource]="data" class="example‐table"
           matSort matSortActive="prod_name" matSortDisableClear matSortDirection="asc">

      <!‐‐ Product Name Column ‐‐>
      <ng‐container matColumnDef="prod_name">
        <th mat‐header‐cell *matHeaderCellDef>Product Name</th>
        <td mat‐cell *matCellDef="let row">{{row.prod_name}}</td>
      </ng‐container>

      <!‐‐ Product Price Column ‐‐>
      <ng‐container matColumnDef="prod_price">
        <th mat‐header‐cell *matHeaderCellDef>Product Price</th>
        <td mat‐cell *matCellDef="let row">$ {{row.prod_price}}</td>
      </ng‐container>

      <tr mat‐header‐row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat‐row *matRowDef="let row; columns: displayedColumns;" [routerLink]="['/product‐details/', row.id]"></tr>
    </table>
  </div>
</div>

Finally, to make a little UI adjustment, open and edit `src/app/products/products.component.css` then add this CSS codes.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 13/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

/* Structure */
.example‐container {
  position: relative;
  padding: 5px;
}

.example‐table‐container {
  position: relative;
  max‐height: 400px;
  overflow: auto;
}

table {
  width: 100%;
}

.example‐loading‐shade {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 56px;
  right: 0;
  background: rgba(0, 0, 0, 0.15);
  z‐index: 1;
  display: flex;
  align‐items: center;
  justify‐content: center;
}

.example‐rate‐limit‐reached {
  color: #980000;
  max‐width: 360px;
  text‐align: center;
}

/* Column Widths */
.mat‐column‐number,
.mat‐column‐state {
  max‐width: 64px;
}

.mat‐column‐created {
  max‐width: 124px;

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 14/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

.mat‐flat‐button {
  margin: 5px;
}

5. Angular 7 Tutorial: Show and Delete Product Details using Angular Material
To show product details after click or tap on the one of a row inside the Angular Material table, open and edit `src/app/product-
detail/product-detail.component.ts` then add this imports.

import { ActivatedRoute, Router } from '@angular/router';
import { ApiService } from '../api.service';
import { Product } from '../product';

Inject above modules to the constructor.

constructor(private route: ActivatedRoute, private api: ApiService, private router: Router) { }

Declare the variables before the constructor for hold product data that get from the API.

product: Product = { _id: '', prod_name: '', prod_desc: '', prod_price: null, updated_at: null };
isLoadingResults = true;

Add a function for getting Product data from the API.

getProductDetails(id) {
  this.api.getProduct(id)
    .subscribe(data => {
      this.product = data;
      console.log(this.product);
      this.isLoadingResults = false;
    });
}

Call that function when the component is initiated.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 15/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

ngOnInit() {
  this.getProductDetails(this.route.snapshot.params['id']);
}

Add this function for delete product.

deleteProduct(id) {
  this.isLoadingResults = true;
  this.api.deleteProduct(id)
    .subscribe(res => {
        this.isLoadingResults = false;
        this.router.navigate(['/products']);
      }, (err) => {
        console.log(err);
        this.isLoadingResults = false;
      }
    );
}

For the view, open and edit `src/app/product-detail/product-detail.component.html` then replace all HTML tags with this.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 16/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

<div class="example‐container mat‐elevation‐z8">
  <div class="example‐loading‐shade"
       *ngIf="isLoadingResults">
    <mat‐spinner *ngIf="isLoadingResults"></mat‐spinner>
  </div>
  <div class="button‐row">
    <a mat‐flat‐button color="primary" [routerLink]="['/products']"><mat‐icon>list</mat‐icon></a>
  </div>
  <mat‐card class="example‐card">
    <mat‐card‐header>
      <mat‐card‐title><h2>{{product.prod_name}}</h2></mat‐card‐title>
      <mat‐card‐subtitle>{{product.prod_desc}}</mat‐card‐subtitle>
    </mat‐card‐header>
    <mat‐card‐content>
      <dl>
        <dt>Product Price:</dt>
        <dd>{{product.prod_price}}</dd>
        <dt>Updated At:</dt>
        <dd>{{product.updated_at | date}}</dd>
      </dl>
    </mat‐card‐content>
    <mat‐card‐actions>
      <a mat‐flat‐button color="primary" [routerLink]="['/product‐edit', product._id]"><mat‐icon>edit</mat‐icon></a>
      <a mat‐flat‐button color="warn" (click)="deleteProduct(product._id)"><mat‐icon>delete</mat‐icon></a>
    </mat‐card‐actions>
  </mat‐card>
</div>

Finally, open and edit `src/app/product-detail/product-detail.component.css` then add this lines of CSS codes.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 17/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

/* Structure */
.example‐container {
  position: relative;
  padding: 5px;
}

.example‐loading‐shade {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 56px;
  right: 0;
  background: rgba(0, 0, 0, 0.15);
  z‐index: 1;
  display: flex;
  align‐items: center;
  justify‐content: center;
}

.mat‐flat‐button {
  margin: 5px;
}

6. Angular 7 Tutorial: Add a Product using Angular Material


To create a form for adding a Product, open and edit `src/app/product-add/product-add.component.ts` then add this imports.

import { Router } from '@angular/router';
import { ApiService } from '../api.service';
import { FormControl, FormGroupDirective, FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';

Inject above modules to the constructor.

constructor(private router: Router, private api: ApiService, private formBuilder: FormBuilder) { }

Declare variables for the Form Group and all of the required fields inside the form before the constructor.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 18/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

productForm: FormGroup;
prod_name:string='';
prod_desc:string='';
prod_price:number=null;
updated_at:Date=null;
isLoadingResults = false;

Add initial validation for each field.

ngOnInit() {
  this.productForm = this.formBuilder.group({
    'prod_name' : [null, Validators.required],
    'prod_desc' : [null, Validators.required],
    'prod_price' : [null, Validators.required],
    'updated_at' : [null, Validators.required]
  });
}

Create a function for submitting or POST product form.

onFormSubmit(form:NgForm) {
  this.isLoadingResults = true;
  this.api.addProduct(form)
    .subscribe(res => {
        let id = res['_id'];
        this.isLoadingResults = false;
        this.router.navigate(['/product‐details', id]);
      }, (err) => {
        console.log(err);
        this.isLoadingResults = false;
      });
}

Next, open and edit `src/app/product-add/product-add.component.html` then replace all HTML tags with this.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 19/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

<div class="example‐container mat‐elevation‐z8">
  <div class="example‐loading‐shade"
       *ngIf="isLoadingResults">
    <mat‐spinner *ngIf="isLoadingResults"></mat‐spinner>
  </div>
  <div class="button‐row">
    <a mat‐flat‐button color="primary" [routerLink]="['/products']"><mat‐icon>list</mat‐icon></a>
  </div>
  <mat‐card class="example‐card">
    <form [formGroup]="productForm" (ngSubmit)="onFormSubmit(productForm.value)">
      <mat‐form‐field class="example‐full‐width">
        <input matInput placeholder="Product Name" formControlName="prod_name"
               [errorStateMatcher]="matcher">
        <mat‐error>
          <span *ngIf="!productForm.get('prod_name').valid && productForm.get('prod_name').touched">Please enter Product Name</span>
        </mat‐error>
      </mat‐form‐field>
      <mat‐form‐field class="example‐full‐width">
        <input matInput placeholder="Product Desc" formControlName="prod_desc"
               [errorStateMatcher]="matcher">
        <mat‐error>
          <span *ngIf="!productForm.get('prod_desc').valid && productForm.get('prod_desc').touched">Please enter Product Description</span>
        </mat‐error>
      </mat‐form‐field>
      <mat‐form‐field class="example‐full‐width">
        <input matInput placeholder="Product Price" formControlName="prod_price"
               [errorStateMatcher]="matcher">
        <mat‐error>
          <span *ngIf="!productForm.get('prod_price').valid && productForm.get('prod_price').touched">Please enter Product Price</span>
        </mat‐error>
      </mat‐form‐field>
      <div class="button‐row">
        <button type="submit" [disabled]="!productForm.valid" mat‐flat‐button color="primary"><mat‐icon>save</mat‐icon></button>
      </div>
    </form>
  </mat‐card>
</div>

Finally, open and edit `src/app/product-add/product-add.component.css` then add this CSS codes.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 20/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

/* Structure */
.example‐container {
  position: relative;
  padding: 5px;
}

.example‐form {
  min‐width: 150px;
  max‐width: 500px;
  width: 100%;
}

.example‐full‐width {
  width: 100%;
}

.example‐full‐width:nth‐last‐child() {
  margin‐bottom: 10px;
}

.button‐row {
  margin: 10px 0;
}

.mat‐flat‐button {
  margin: 5px;
}

7. Angular 7 Tutorial: Edit a Book using Angular Material


We have put an edit button inside the Product Detail component for call Edit page. Now, open and edit `src/app/product-
edit/product-edit.component.ts` then add this imports.

import { Router, ActivatedRoute } from '@angular/router';
import { ApiService } from '../api.service';
import { FormControl, FormGroupDirective, FormBuilder, FormGroup, NgForm, Validators } from '@angular/forms';

Inject above modules to the constructor.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 21/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

constructor(private router: Router, private route: ActivatedRoute, private api: ApiService, private formBuilder: FormBuilder) { }

Declare the Form Group variable and all of the required variables for the product form before the constructor.

productForm: FormGroup;
_id:string='';
prod_name:string='';
prod_desc:string='';
prod_price:number=null;
isLoadingResults = false;

Next, add validation for all fields when the component is initiated.

ngOnInit() {
  this.getProduct(this.route.snapshot.params['id']);
  this.productForm = this.formBuilder.group({
    'prod_name' : [null, Validators.required],
    'prod_desc' : [null, Validators.required],
    'prod_price' : [null, Validators.required]
  });
}

Create a function for getting product data that filled to each form fields.

getProduct(id) {
  this.api.getProduct(id).subscribe(data => {
    this._id = data._id;
    this.productForm.setValue({
      prod_name: data.prod_name,
      prod_desc: data.prod_desc,
      prod_price: data.prod_price
    });
  });
}

Create a function to update the product changes.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 22/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

onFormSubmit(form:NgForm) {
  this.isLoadingResults = true;
  this.api.updateProduct(this._id, form)
    .subscribe(res => {
        let id = res['_id'];
        this.isLoadingResults = false;
        this.router.navigate(['/product‐details', id]);
      }, (err) => {
        console.log(err);
        this.isLoadingResults = false;
      }
    );
}

Add a function for handling show product details button.

productDetails() {
  this.router.navigate(['/product‐details', this._id]);
}

Next, open and edit `src/app/product-edit/product-edit.component.html` then replace all HTML tags with this.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 23/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

<div class="example‐container mat‐elevation‐z8">
  <div class="example‐loading‐shade"
       *ngIf="isLoadingResults">
    <mat‐spinner *ngIf="isLoadingResults"></mat‐spinner>
  </div>
  <div class="button‐row">
    <a mat‐flat‐button color="primary" (click)="productDetails()"><mat‐icon>info</mat‐icon></a>
  </div>
  <mat‐card class="example‐card">
    <form [formGroup]="productForm" (ngSubmit)="onFormSubmit(productForm.value)">
      <mat‐form‐field class="example‐full‐width">
        <input matInput placeholder="Product Name" formControlName="prod_name"
               [errorStateMatcher]="matcher">
        <mat‐error>
          <span *ngIf="!productForm.get('prod_name').valid && productForm.get('prod_name').touched">Please enter Product Name</span>
        </mat‐error>
      </mat‐form‐field>
      <mat‐form‐field class="example‐full‐width">
        <input matInput placeholder="Product Desc" formControlName="prod_desc"
               [errorStateMatcher]="matcher">
        <mat‐error>
          <span *ngIf="!productForm.get('prod_desc').valid && productForm.get('prod_desc').touched">Please enter Product Description</span>
        </mat‐error>
      </mat‐form‐field>
      <mat‐form‐field class="example‐full‐width">
        <input matInput placeholder="Product Price" formControlName="prod_price"
               [errorStateMatcher]="matcher">
        <mat‐error>
          <span *ngIf="!productForm.get('prod_price').valid && productForm.get('prod_price').touched">Please enter Product Price</span>
        </mat‐error>
      </mat‐form‐field>
      <div class="button‐row">
        <button type="submit" [disabled]="!productForm.valid" mat‐flat‐button color="primary"><mat‐icon>save</mat‐icon></button>
      </div>
    </form>
  </mat‐card>
</div>

Finally, open and edit `src/app/product-edit/product-edit.component.css` then add this lines of CSS codes.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 24/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

/* Structure */
.example‐container {
  position: relative;
  padding: 5px;
}

.example‐form {
  min‐width: 150px;
  max‐width: 500px;
  width: 100%;
}

.example‐full‐width {
  width: 100%;
}

.example‐full‐width:nth‐last‐child() {
  margin‐bottom: 10px;
}

.button‐row {
  margin: 10px 0;
}

.mat‐flat‐button {
  margin: 5px;
}

8. Angular 7 Tutorial: Run and Test the Angular 7 CRUD Web Application
Now, it's a time for testing the Angular 7 CRUD Web Application. First, we have to run MongoDB server in another Terminal tab.

mongod

Open the other Terminal tab again then run the cloned Express.js API.

npm start

Back to the current Terminal tab, then run the Angular 7 Web Application.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 25/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

Block ads without extensions

DOWNLOAD
Ad

ng serve

In the browser go to this URL `localhost:4200` and here the whole application looks like.

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 26/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 27/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

That it's, we have finished the Angular 7 Tutorial: Building CRUD Web Application. If you can't follow the steps of the tutorial,
you can compare it with the working source code from our GitHub (https://github.com/didinj/angular7-material-crud-
example.git).
That just the basic. If you need more deep learning about MEAN Stack, Angular, and Node.js, you can take the following cheap
course:

Angular (Angular 2+) & NodeJS - The MEAN Stack Guide (https://click.linksynergy.com/link?
id=6nYo96*QrJE&offerid=358574.833442&type=2&murl=https%3A%2F%2Fwww.udemy.com%2Fangular-2-and-nodejs-the-
practical-guide%2F)
Start Building Web Apps And Services With Node. js + Express (https://click.linksynergy.com/link?
id=6nYo96*QrJE&offerid=358574.150396&type=2&murl=https%3A%2F%2Fwww.udemy.com%2Fthe-ultimate-guide-to-
nodejs-express%2F)
https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 28/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

Build a REST API with node. js, ExpressJS, and MongoDB (https://click.linksynergy.com/link?
id=6nYo96*QrJE&offerid=358574.654736&type=2&murl=https%3A%2F%2Fwww.udemy.com%2Fnodejs-api%2F)
Angular 5 Bootcamp FastTrack (https://click.linksynergy.com/link?
id=6nYo96*QrJE&offerid=358574.1461406&type=2&murl=https%3A%2F%2Fwww.udemy.com%2Fangular-bootcamp-
fasttrack%2F)
Angular 6 - Soft & Sweet (https://click.linksynergy.com/link?
id=6nYo96*QrJE&offerid=507388.1668070&type=2&murl=https%3A%2F%2Fwww.udemy.com%2Fangular-soft-and-
sweet%2F)
Angular 6 with TypeScript (https://click.linksynergy.com/link?
id=6nYo96*QrJE&offerid=507388.1757238&type=2&murl=https%3A%2F%2Fwww.udemy.com%2Fangular6withtypescript%2F)

Thanks!
 

Follow

(http://www.facebook.com/djamwarecom)

(http://twitter.com/intent/follow?source=followbutton&variant=1.0&screen_name=djamware)

(http://www.pinterest.com/djamware) (http://www.linkedin.com/in/didin-jamaludin-7a530351)

(http://www.youtube.com/channel/UCtI81hYLh2Ae_45KHkyy0vw?sub_confirmation=1) (https://github.com/didinj)

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 29/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

Block ads without extensions

DOWNLOAD
Ad
(https://www.ezoic.com/what-is-
ezoic/)
report this ad

 Previous Article
Vue.js Firebase Tutorial: Build Firestore CRUD Web Application

(/post/5bc9313680aca7466989441e/vuejs-firebase-tutorial-build-firestore-crud-web-application)

Next Article 
Angular 7 Tutorial: Create Angular Material CDK Virtual Scroll

(/post/5bd2dce880aca70a40ccc401/angular-7-tutorial-create-angular-material-cdk-virtual-scroll)

Related Articles
Node, Express, React.js, Graphql and MongoDB CRUD Web Application (/post/5cbd1e9a80aca754f7a9d1f2/node-
express-reactjs-graphql-and-mongodb-crud-web-application)
Node.js, Express.js and Multer Restful API for Image Uploader (/post/5c98220080aca754f7a9d1f0/nodejs-expressjs-
and-multer-restful-api-for-image-uploader)
Node, Express, Angular 7, GraphQL and MongoDB CRUD Web App (/post/5c75d68880aca754f7a9d1ed/node-express-

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 30/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

angular-7-graphql-and-mongodb-crud-web-app)
Secure Node.js, Express.js and PostgreSQL API using Passport.js (/post/5bf94d9a80aca747f4b9ce9f/secure-nodejs-
expressjs-and-postgresql-api-using-passportjs)
Angular 7 Tutorial: Create Angular Material CDK Virtual Scroll (/post/5bd2dce880aca70a40ccc401/angular-7-tutorial-
create-angular-material-cdk-virtual-scroll)
Vue.js Firebase Tutorial: Build Firestore CRUD Web Application (/post/5bc9313680aca7466989441e/vuejs-firebase-
tutorial-build-firestore-crud-web-application)
React.js Firebase Tutorial: Building Firestore CRUD Web Application (/post/5bc50ea680aca7466989441d/reactjs-
firebase-tutorial-building-firestore-crud-web-application)
Angular 6 Firebase Tutorial: Firestore CRUD Web Application (/post/5bbf534580aca7466989441c/angular-6-firebase-
tutorial-firestore-crud-web-application)
Node, Express, Sequelize, and PostgreSQL Association Example (/post/5bb1f05280aca74669894417/node-express-
sequelize-and-postgresql-association-example)
Angular 6 HttpClient: Consume RESTful API Example (/post/5b87894280aca74669894414/angular-6-httpclient-
consume-restful-api-example)
MongoDB, Express, Vue.js 2, Node.js (MEVN) and SocketIO Chat App (/post/5b6a681f80aca76a2cbd98fb/mongodb-
express-vuejs-2-nodejs-mevn-and-socketio-chat-app)
Node.js, Express.js, Sequelize.js and PostgreSQL RESTful API (/post/5b56a6cc80aca707dd4f65a9/nodejs-expressjs-
sequelizejs-and-postgresql-restful-api)

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 31/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

Sponsored Links

La casa de Kate del Castillo no es lo que esperabas
Revista Glamur

World's Scariest Bridges
Viral X Files

11 Most Isolated Places At The End Of The Earth
Relocation Target

7 Danger Signs of Prediabetes You Are Probably Ignoring in Venezuela
Health & Human Research

11 Cancer Causing Foods You Should Avoid
Nutrition Expert

PHOTOS: These are the 10 richest countries in the world

9 Comments Djamware ­ Fullstack Programming Tutorials 
1 Login

  Recommend t Tweet f Share Sort by Best

Join the discussion…

LOG IN WITH
OR SIGN UP WITH DISQUS  ?

Name

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 32/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

Bob Kline • 6 months ago
You've got some discrepancies between the tutorial instructions and what you've got in GitHub. For example, throughout the tutorial, you talk about
editing .css files, but I think you meant .scss files. For another example, in `api.service.ts` the `getProducts()` method has `tap(heroes =>
console.log('fetched products')),` where the GitHub code has `tap(products => console.log('Fetch products')),`. I expect I may find more differences
as I track down the compilation errors I'm getting.
3 △   ▽ • Reply • Share ›

oam4ever • 2 months ago
This tutorial is full of errors and following the instructions on it doesn't yield the desired output. It needs revising. Most people who try it are Angular
beginners and it just frustrates them.
2 △   ▽ • Reply • Share ›

Jeevan • 6 months ago
Please change the Product id as _id : string in Product.ts class according to the Git repository. and i think there may be few mismatches between this
tutorial and your github repository
1 △   ▽ • Reply • Share ›

Abhishek Nikam • 22 days ago
getting error at let id = res['id']; in product­add.component.ts file
△   ▽ • Reply • Share ›

Himanshu gupta • 22 days ago
routing error this code not proper error free
△   ▽ • Reply • Share ›

Himanshu gupta • 22 days ago
error for this code please solve


https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 33/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

△   ▽ • Reply • Share ›

bouslamamo • 4 months ago
Hello,
how to install the express and mongodb plz ?
△   ▽ • Reply • Share ›

Hendi Santika • 6 months ago
I've got this error :

Hendis­MacBook­Pro­2:angular7­crud hendisantika$ ng add @angular/material
Installing packages for tooling via npm.
The package that you are trying to add does not support schematics. You can try using a different version of the package or contact the package
author to add ng­add support.

Any suggestion?
Thanks
△   ▽ • Reply • Share ›

Yogi • 6 months ago
Ditunggu tutorial mogodb dan express jsnya bang... untuk angular 7...
△   ▽ • Reply • Share ›

ALSO ON DJAMWARE ­ FULLSTACK PROGRAMMING TUTORIALS

Ionic 4 and Angular 6 Tutorial: Firebase Realtime CRUD Mobile Building CRUD Mobile App using Ionic 4, Angular 6 and Cordova
App 21 comments • 9 months ago
12 comments • 8 months ago
Avatarmohd sadiq — Thank you so much for taking time to write such a great
AvatarEdgar Garriga — Sorry, but it seems it doenst work the connection tutorial on ionic 4 CURD.
between ionic and firebase.I copy the …

Securing RESTful API with Spring Boot, Security, and Data MongoDB, Express, Vue.js 2, Node.js (MEVN) and SocketIO Chat
MongoDB
https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application
App 34/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application
MongoDB App
1 comment • 2 months ago 7 comments • 9 months ago

AvatarAashik Ahamed — can u put the raw data image for AvatarKaveesh — Thanks a lot
localhost:8080/api/auth/register …

✉ Subscribe d Add Disqus to your siteAdd DisqusAdd ὑ Disqus' Privacy PolicyPrivacy PolicyPrivacy

(https://www.ezoic.com/what-is-ezoic/)

report this ad

Programming Blog
(/post-category/595f867edbd39e7571e183dc/programming-blog)
HTML 5 Tutorial
(/post-sub-category/584209dffcbe618f680bdc5c/html-5-tutorial)
MongoDB
https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 35/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

(/post-sub-category/5845677b80aca7763489d871/mongodb)
Javascript
(/post-sub-category/583d6d30fcbe614473a4c4e9/javascript)
ASP.NET Core
(/post-sub-category/5c50643780aca754f7a9d1e9/aspnet-core)
Groovy and Grails
(/post-sub-category/585b3fa380aca73b19a2efd4/groovy-and-grails)
Ionic Framework
(/post-sub-category/5845691a80aca7763489d872/ionic-framework)
React Native
(/post-sub-category/5b4aa0b480aca707dd4f65a6/react-native)
Java
(/post-sub-category/583d6c37fcbe614473a4c4e8/java)
CSS 3
(/post-sub-category/584249bde4d5d303658d1ecf/css-3)
Node.js
(/post-sub-category/58a9196f80aca748640ce352/nodejs)
All Articles
(/public/allArticles)

Popular Articles:
Angular 7 Tutorial: Building CRUD Web Application
(/post/5bca67d780aca7466989441f/angular-7-tutorial-building-crud-web-application)
Angular 6 HttpClient: Consume RESTful API Example
(/post/5b87894280aca74669894414/angular-6-httpclient-consume-restful-api-example)
Securing RESTful API with Spring Boot, Security, and Data MongoDB
(/post/5c819d0180aca754f7a9d1ee/securing-restful-api-with-spring-boot-security-and-data-mongodb)
Ionic 4, Angular 7 and Cordova Tutorial: Build CRUD Mobile Apps
(/post/5be52ce280aca72b942e31bc/ionic-4-angular-7-and-cordova-tutorial-build-crud-mobile-apps)

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 36/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

Node, Express, Angular 7, GraphQL and MongoDB CRUD Web App


(/post/5c75d68880aca754f7a9d1ed/node-express-angular-7-graphql-and-mongodb-crud-web-app)
Building CRUD Mobile App using Ionic 4, Angular 6 and Cordova
(/post/5b5cffaf80aca707dd4f65aa/building-crud-mobile-app-using-ionic-4-angular-6-and-cordova)
Building Web App using ASP.NET Web API Angular 7 and SQL Server
(/post/5c50e5f280aca754f7a9d1eb/building-web-app-using-aspnet-web-api-angular-7-and-sql-server)
Ionic 3, Angular 4 and SQLite CRUD Offline Mobile App
(/post/59c53a1280aca768e4d2b143/ionic-3-angular-4-and-sqlite-crud-offline-mobile-app)
Ionic 4 and Angular 7 Tutorial: HTTP Interceptor Example
(/post/5c42ca7580aca754f7a9d1e8/ionic-4-and-angular-7-tutorial-http-interceptor-example)
How to Upload File on Ionic 3 using Native File Transfer Plugin
(/post/599da16580aca768e4d2b130/how-to-upload-file-on-ionic-3-using-native-file-transfer-plugin)

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 37/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

(https://www.ezoic.com/what-
is-ezoic/)
report this ad

©2012-2018 Djamware.com (http://Djamware.com) | Privacy Policy (/public/privacy) | About Us (/public/about) | Contact Us (/public/contact) | RSS
(https://www.djamware.com/feeds)

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 38/39
27/4/2019 Angular 7 Tutorial: Building CRUD Web Application

https://www.djamware.com/post/5bca67d780aca7466989441f/angular­7­tutorial­building­crud­web­application 39/39

You might also like