import { Component , OnInit } from '@angular/core' ; import { Router , ActivatedRoute } from '@angular/router' ; import { ApiService } from '../api.service' ; import { FormControl , FormGroupDirective , FormBuilder , FormGroup , NgForm , Validators } from '@angular/forms' ; @ Component ( { selector : 'app-product-edit' , templateUrl : './product-edit.component.html' , styleUrls : [ './product-edit.component.scss' ] } ) export class ProductEditComponent implements OnInit { productForm : FormGroup ; _id : string = '' ; prod_name : string = '' ; prod_desc : string = '' ; prod_price : number = null ; isLoadingResults = false ; constructor ( private router , private route , private api , private formBuilder ) { } 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 ] } ) ; } 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 } ) ; } ) ; } onFormSubmit ( form ) { 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 ; } ) ; } productDetails ( ) { this . router . navigate ( [ '/product-details' , this . _id ] ) ; } }