Angular 9 CRUD | Part 7 | Update an Existing Product

0
747
Angular 9 CRUD

In this article, we will update the existing product details in Angular 9 CRUD Application. Here we are using reactive forms and HttpClient for updating the product details.

A component class file like this

import { Component, OnInit } from '@angular/core';
import {Products} from '../../models/products';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {CrudService} from '../../services/crud.service';
import {ActivatedRoute, Router} from '@angular/router';

@Component({
  selector: 'app-update',
  templateUrl: './update.component.html',
  styleUrls: ['./update.component.scss']
})
export class UpdateComponent implements OnInit {
  productForm: FormGroup;
  productID: any;
  productData: Products;
  constructor(
    private fb: FormBuilder,
    private crudService: CrudService,
    private router: Router,
    private actRoute: ActivatedRoute) {
    this.productForm = this.fb.group({
      name: ['', Validators.required],
      desc: ['', Validators.compose([Validators.required, Validators.minLength(10), Validators.maxLength(1000)])],
      price: ['', Validators.compose([Validators.required])],
    });
// code
  }

  ngOnInit() {
    this.productID = this.actRoute.snapshot.params.id;
    this.loadProductDetails(this.productID);
  }

  loadProductDetails(productID) {
    this.crudService.getProductDetails(productID).subscribe(product => {
      this.productData = product;
      this.productForm.controls.name.setValue(this.productData.p_name);
      this.productForm.controls.desc.setValue(this.productData.p_description);
      this.productForm.controls.price.setValue(this.productData.p_price);
    });
  }

  updateProductData(values) {
    const productData = new FormData();
    productData.append('id', this.productID);
    productData.append('name', values.name);
    productData.append('description', values.desc);
    productData.append('price', values.price);
    this.crudService.updateProduct(productData).subscribe(result => {
      this.router.navigate(['']);
    });
  }}


First Inject the following services into the constructor using DI.

constructor(
private fb: FormBuilder,
private crudService: CrudService,
private router: Router,
private actRoute: ActivatedRoute)

Get the product id from the route using the following code

this.productID = this.actRoute.snapshot.params.id;

Create a method for loading product details and the method into the ngOnInit method.

loadProductDetails(productID) {
  this.crudService.getProductDetails(productID).subscribe(product => {
    this.productData = product;
    this.productForm.controls.name.setValue(this.productData.p_name);
    this.productForm.controls.desc.setValue(this.productData.p_description);
    this.productForm.controls.price.setValue(this.productData.p_price);
  });
}


Once the product value comes from the web API, we need to set that values to the form controls

this.productForm.controls['name'].setValue(this.productData['p_name']);
this.productForm.controls['desc'].setValue(this.productData['p_description']);
this.productForm.controls['price'].setValue(this.productData['p_price']);

Create another one method for update the product details

updateProductData(values){
const productData = new FormData();
productData.append('id', this.productID);
productData.append('name', values.name);
productData.append('description', values.desc);
productData.append('price', values.price);
this.crudService.updateProduct(productData).subscribe(result=>{
this.router.navigate(['']);
})
}

Here I am using form data to combine the value in post format

const productData = new FormData();
productData.append('id', this.productID);
productData.append('name', values.name);
productData.append('description', values.desc);
productData.append('price', values.price);

Then call the update service to update the product

this.crudService.updateProduct(productData).subscribe();

Your template file like this

<div class="container-fluid">
  <div class="row">
    <div class="col-12 col-lg-12 col-md-12 sol-sm-12">
      <form [formGroup]="productForm" (ngSubmit)="updateProductData(productForm.value)">

        <div class="form-group">
          <label>Name</label>
          <input type="text" class="form-control" placeholder="Enter Name" formControlName="name" required>
          <div class="alert-danger" *ngIf="!productForm.controls['name'].valid && (productForm.controls['name'].touched)">
            <div [hidden]="!productForm.controls['name'].errors.required">
              Name is required.
            </div>
          </div>
        </div>

        <div class="form-group">
          <label>Desc</label>
          <input type="text" class="form-control" placeholder="Description" formControlName="desc" required>
          <div class="alert-danger" *ngIf="!productForm.controls['desc'].valid && (productForm.controls['desc'].touched)">
            <div [hidden]="!productForm.controls['desc'].errors.required">
              Description is required.
            </div>
            <div [hidden]="!productForm.controls['desc'].errors.minlength">
              Description must be have 10 character length.
            </div>
          </div>
        </div>

        <div class="form-group">
          <label>Price</label>
          <input type="number" class="form-control" placeholder="price" formControlName="price" required>
          <div class="alert-danger" *ngIf="!productForm.controls['price'].valid && (productForm.controls['price'].touched)">
            <div [hidden]="!productForm.controls['price'].errors.required">
              Price is required.
            </div>
          </div>
        </div>

        <button type="submit" class="btn btn-primary" [disabled]="!productForm.valid">Submit</button>

      </form>
    </div>
  </div>
</div>
  1. Angular 9 CRUD | Part 1 | Project Creation and Theme Integration
  2. Angular 9 CRUD | Part 2 | Web API Preparation
  3. Part 3 | Creating Web Services using HttpClient
  4. Part 4 | Display the Products
  5. Part 5 | View Single Product Details
  6. Part 6 | Create New Product
  7. Part 7 | Update an Existing Product
  8. Part 8 |Delete an Existing Product