import { Component , OnInit , ViewChild } from '@angular/core' ; import { Router , ActivatedRoute } from '@angular/router' ; import { NgForm } from '@angular/forms' ; import { IProduct } from '../product' ; import { ProductService } from '../product.service' ; @ Component ( { templateUrl : './product-edit.component.html' , styleUrls : [ './product-edit.component.css' ] } ) export class ProductEditComponent implements OnInit { @ ViewChild ( NgForm ) editForm : NgForm ; pageTitle : string = 'Product Edit' ; errorMessage : string ; private originalProduct : IProduct ; product : IProduct ; get isDirty ( ) : boolean { return this . editForm . dirty ? true : false ; } constructor ( private productService , private router , private route ) { } ngOnInit ( ) { this . route . params . subscribe ( params => { const id = + params [ 'id' ] ; this . getProduct ( id ) ; } ) ; } getProduct ( id ) { this . productService . getProduct ( id ) . subscribe ( product => this . onProductRetrieved ( product ) , error => this . errorMessage = < any > error ) ; } onProductRetrieved ( product ) { this . editForm . reset ( ) ; this . originalProduct = product ; this . product = Object . assign ( { } , product ) ; if ( this . product . id === 0 ) { this . pageTitle = 'Add Product' ; } else { this . pageTitle = `Edit Product: ${ this . product . productName }` ; } } cancel ( ) { this . router . navigate ( [ '/products' ] ) ; } deleteProduct ( ) { if ( this . product . id ) { if ( confirm ( `Really delete the product: ${ this . product . productName }?` ) ) { this . productService . deleteProduct ( this . product . id ) . subscribe ( ( ) => this . onSaveComplete ( ) , ( error ) => this . errorMessage = < any > error ) ; } } else { this . onSaveComplete ( ) ; } } saveProduct ( ) { if ( this . editForm . valid ) { this . productService . saveProduct ( this . product ) . subscribe ( ( ) => { Object . keys ( this . product ) . forEach ( key => this . originalProduct [ key ] = this . product [ key ] ) ; this . onSaveComplete ( ) ; } , ( error ) => this . errorMessage = < any > error ) ; } else { this . errorMessage = 'Please correct the validation errors.' ; } } onSaveComplete ( ) { this . editForm . reset ( this . editForm . value ) ; this . router . navigate ( [ '/products' ] ) ; } }