Json data to be represented in formcontrol in angular 5 - html

I am trying to bind the Json value which I get from my server to respective textboxes,but when I bind I see the value in textbox as [object object]
<h1>{{title}}</h1>
<h3>Catalog</h3>
<hr />
<fieldset>
<legend>About Tool</legend>
<form [formGroup]="CatalogForm" #formDir="ngForm" novalidate>
<div class="form-group row">
<!-- <div *ngIf="ItemName != null"></div>-->
<!--<div *ngFor="let c of CatalogForm;let i=index"></div>-->
<label class="control-label col-md-12">ItemName</label>
<div class="col-md-4"></div>
<input class="form-control" readonly="true" type="text" formControlName="Category" >
<pre>{{CatalogForm.value.Category | json }}</pre>
</div>
<br /><br/>
</form>
</form>
and my component code is
import { Component, OnInit } from '#angular/core';
import { Http, Headers } from '#angular/http';
import { FormsModule,NgForm, FormBuilder, FormGroup, Validators, FormControl } from '#angular/forms';
import { Router, ActivatedRoute } from '#angular/router';
import { CatalogComponent } from '../catalog/catalog.component';
import { CatalogService } from '../services/Catalog.service';
import { ContactService } from '../services/Contact.service';
import { URLService } from '../services/URL.service';
import { SupportService } from '../services/Support.service';
import { Catalog } from '../classes/Catalog';
import { Contact } from '../classes/Contact';
import { URL } from '../classes/URL';
import { Support } from '../classes/Support';
import { Category } from '../classes/Category';
#Component({
selector: 'app-catalog-form',
templateUrl: './catalog-form.component.html',
styleUrls: ['./catalog-form.component.scss']
})
export class CatalogFormComponent implements OnInit {
Catalogdata:Catalog;
Contacts:Contact[];
URLs:URL[];
Supportdata:Support[];
CatalogForm:FormGroup;
title: string = "";
id: number;
errorMessage: any;
constructor( private _fb: FormBuilder,private _avRoute: ActivatedRoute,
private catService: CatalogService,private conservice:ContactService,
private urlservice:URLService,private supservice:SupportService, private _router: Router) {
if (this._avRoute.snapshot.params["id"]) {
this.id = this._avRoute.snapshot.params["id"];
}
this.CatalogForm = this._fb.group({
Category: [''],
SubCategory:[''],
ItemName:[''],
Description:[''],
IAP_Number:[''],
/*ToolOwner:[''],
BusinessOwner:[''],
ProdURL:[''],
IncidentURL:[''],
RequestURL:[''],
SupportType:[''],
SupportValue:[''],
SupportLink:['']*/
})
}
ngOnInit() {
console.log("I am in form component",this.id);
if (this.id > 0) {
this.title = "View";
console.log("Title of form:",this.title) ;
this.catService.getCatalogDetails(this.id)
.subscribe( t =>
this.CatalogForm.patchValue
({Category:t,SubCategory:t,Description:t,ItemName:t,IAP_Number:t}) , err =>
console.log("Error messgae:",this.errorMessage)
);
}
console.log("Catalog and Category Details:",this.CatalogForm);
//.controls.Category.
//get(['cItem']));
}
cancel() {
this._router.navigate(['/home']);
}
//get ItemName() {return this.CatalogForm.get('Category').value; }
}
The <pre>{{CatalogForm.value.Category | json }}</pre>
gives me below data in JSON
[
{
"cats": {
"category_Id": 3,
"category_Name": "abc",
"sub_Category": "mmm"
},
"cItem": {
"catalog_Item_Id": 1,
"category_Id": 3,
"item_Name": "hsdd",
"description": "sadss",
"popularity_Flag": true,
"iaP_No": null,
"categoryID": {
"category_Id": 3,
"category_Name": "sds",
"sub_Category": "sad"
}
}
}
]
My problem is how to show the category_Name valuein a textbox.Here the json has category_name as abc and I want to bind that value to category_name textbox as its value. can you take a look?

Try:
<input
class="form-control"
readonly="true"
type="text"
formControlName="Category"
[ngModel]="CatalogForm.value.Category[0].cats.category_Name">
Use [(ngModel)] for 2 way binding

Related

How to get the values of multiple checkboxes in Angular 8

I am trying to get the values of the checkboxes that are selected. I have the following code:
<div style="background-color:lightblue;" >
<div class="content">
<label class="label">Province</label>
<div class="form-check form-check-inline" *ngFor = "let province of utilities.Provinces; let i of index">
<label class="form-check-label" for="inlineCheckbox1" >{{province}}</label>
<input class="form-check-input" [formControl]= "province" (change)="getSelectedProvinces()" type="checkbox" id="inlineCheckbox{{i}}" value="option1">
</div>
</div>
In .ts I have the following
import { Component, OnInit } from '#angular/core';
import { UtilitiesService } from '../_services/utilities.service';
import { Utilities } from '../models/utilities';
import { forEach } from '#angular/router/src/utils/collection';
#Component({
selector: 'app-filtering',
templateUrl: './filtering.component.html',
styleUrls: ['./filtering.component.css']
})
export class FilteringComponent implements OnInit {
utilities: Utilities;
provinces: string[] = [];
selectedProvinces: string[] = [];
selectedCategories: string[] = [];
constructor(private utilityService: UtilitiesService) { }
ngOnInit() {
this.loadUtilities();
}
loadUtilities() {
this.utilityService.getJSON().subscribe((utilities: Utilities) => {
this.utilities = utilities;
});
for (const province of this.utilities.Provinces) {
this.provinces.push(province);
}
}
getSelectedProvinces() {
this.selectedProvinces = [];
this.utilities.Provinces.forEach((_province, i) => {
if (_province.value) {
this.selectedProvinces.push(this.provinces[i]);
}
});
console.log(this.selectedProvinces);
}
}
In my utilities.ts I have the following:
export interface Utilities {
Provinces: Array<string>;
}
My service is written as follows:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Utilities } from '../models/utilities';
import { Observable } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class UtilitiesService {
constructor(private http: HttpClient) {}
public getJSON(): Observable<Utilities> {
return this.http.get<Utilities>('./assets/utilities.json');
}
}
The Json that is has the following content:
{
"Provinces":["East","North West","North"]
}
When I try that, I have the following error:
TypeError: Cannot read property 'Provinces' of undefined.
The thing is, when I remove [formControl]= "province" (change)="getSelectedProvinces()", at least I am able to display the provinces on my page.
How can I go about this?
I finally solved my problem using this code below:
<div class="content">
<label class="label">Province</label>
<div class="form-check form-check-inline" *ngFor="let province of utilities.Provinces">
<label class="form-check-label" for="{{province}}">{{province}}</label>
<input class="form-check-input" (change)="onChangeCategory(province, $event.target.checked)"name="{{ province}}" type="checkbox" id="{{province}}">
</div>
In my .ts, I have the following:
onChangeProvince(province: string, isChecked: boolean) {
if (isChecked) {
this.selectedProvinces.push(province);
} else {
const index = this.selectedProvinces.indexOf(province);
this.selectedProvinces.splice(index, 1);
}
console.log(this.selectedProvinces);
}

How to show error message for typing in text box any thing else except number / numeric in angular 8

I have a text box,which only allows to type number,If I try to type alphabet or any special character it should show error below the text box.Once I start typing numeric error should hide.Here I am using reactive form of angular 8. Here is the code below
home.component.html
<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
<div class="form-row">
<div class="form-group col">
<label>Title</label>
<input type="number" formControlName="title" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.title.errors }"/>
<div *ngIf="submitted && f.title.errors" class="invalid-feedback">
<div *ngIf="f.title.errors.required">Title is required</div>
</div>
</div>
</div>
<div class="text-center">
<button class="btn btn-primary mr-1">Register</button>
<button class="btn btn-secondary" type="reset" >Cancel</button>
</div>
</form>
home.component.ts
import { Component, OnInit } from '#angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '#angular/forms';
import {NgbModal, ModalDismissReasons} from '#ng-bootstrap/ng-bootstrap';
declare var $: any;
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
imageSource :any;
statusdata: any;
closeResult: string;
registerForm: FormGroup;
submitted = false;
constructor(private modalService: NgbModal,private formBuilder: FormBuilder) {}
ngOnInit() {
this.statusdata = [
{ id: 1, name: "cat"},
{ id: 2, name: "arctichare"},
{ id: 3, name: "baboon" },
];
this.registerForm = this.formBuilder.group({
title: ['', Validators.required]
});
}
get f() { return this.registerForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
return;
}
// display form values on success
alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.registerForm.value, null, 4));
}
}
app.module.ts
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { UsermanagementComponent } from './usermanagement/usermanagement.component';
import { HomeComponent } from './home/home.component';
import { HeaderComponent } from './shared/header/header.component';
import { LoginComponent } from './login/login.component';
import {HttpModule} from '#angular/http';
import { FormsModule,ReactiveFormsModule } from '#angular/forms';
import {NgbModule} from '#ng-bootstrap/ng-bootstrap';
#NgModule({
declarations: [
AppComponent,
UsermanagementComponent,
HomeComponent,
HeaderComponent,
LoginComponent
],
imports: [
NgbModule,
BrowserModule,
AppRoutingModule,
HttpModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I think you can catch input values with keydown or keyup.
change your input as following:
<input type="number" formControlName="title" class="form-control"
#inp (keydown)="checkValue($event, inp.value)"
[ngClass]="{ 'is-invalid': submitted && f.title.errors }"/>
And add following method to your component:
checkValue(event: KeyboardEvent, val: any) {
const allowedChars = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, "Backspace", "ArrowLeft", "ArrowRight"];
let isValid: boolean = false;
for (let i = 0; i < allowedChars.length; i++) {
if (allowedChars[i] == event.key) {
isValid = true;
break;
}
}
if (!isValid) {
event.preventDefault();
alert('Enter only number'); // or do smt about your error message
}else{
//reset error status here
}
}

How to post an object to an array in a json using Angular 6

So I'm testing Angular 6 functionality out for fun to learn it and running a json-server to load a db.json to a localhost server to acquire via service calls which you can see here
{
"customers": {
"testingTitle": "Testing Title",
"trainData":[
{
"id": 1,
"name": "Test Name 1",
"email": "customer001#email.com",
"tel": "0526252525"
},
{
"id": 2,
"name": "Test Name 2",
"email": "customer002#email.com",
"tel": "0527252525"
},
{
"id": 3,
"name": "Customer003",
"email": "customer003#email.com",
"tel": "0528252525"
},
{
"id": 4,
"name": "123",
"email": "123",
"tel": "123"
}
]
}
I have a test.service.ts as followed which picks up the service:
import { Injectable } from '#angular/core';
import {HttpClient, HttpResponse, HttpErrorResponse, HttpHeaders, HttpParams} from '#angular/common/http';
import { Observable } from 'rxjs/Rx';
import { catchError, map } from 'rxjs/operators';
import 'rxjs/add/observable/throw';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
class Test {
testingTitle: string;
trainData:[
{
id : number;
name: string;
email: string;
tel: string;
}
];
}
#Injectable({providedIn: 'root'})
export class TestService {
constructor(private http: HttpClient) {}
public getAllTests(): Observable<Test[]>{
const params = new HttpParams().set('_page', "*").set('_limit', "*");
return this.http.get<Test[]>("http://localhost:3000/customers", {params}).pipe(map(res => res));
}
public postTests(object) {
return this.http.post("http://localhost:3000/customers", object).subscribe(data => {console.log("POST Request is successful ", data);},error => {console.log("Error", error);});
}
}
I have my test.ts which controls my calls etc.
import { Component, OnInit } from '#angular/core';
import { HttpClient } from "#angular/common/http";
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import {FormBuilder, FormControl, FormGroup} from "#angular/forms";
import {TestService} from "./test.service";
class Customer {
id : number;
name: string;
email: string;
tel: string;
}
#Component({
selector: 'sample-template',
templateUrl: './test.component.html'})
export class TestComponent implements OnInit {
testForm: FormGroup;
testForm2: FormGroup;
public test: any;
name: string = '';
email: string = '';
tel: string = '';
public id: any;
constructor(private httpClient:HttpClient, private fb: FormBuilder, private TestService: TestService) {}
loadTasks(): void{
this.TestService.getAllTests().subscribe(response => {this.test = response;
console.log(this.test)})
}
ngOnInit() {
let trainData = [];
this.loadTasks();
this.testForm = this.fb.group({
testCd: 'Select'
});
this.testForm2 = this.fb.group({
id: this.id,
name: this.name,
email: this.email,
tel: this.tel
})
}
changeDropdown(formControl: FormControl, option: string): void {
formControl.patchValue(option);
console.log(option);
}
submitForm(){
let last:any = this.test[this.test.length-1];
this.id = last.id+1;
console.log(this.id);
this.testForm2.value.id = this.id;
console.log(this.testForm2.value);
this.TestService.postTests(this.testForm2.value);
}
}
And my html page which includes the following:
<label class="modelo-label">{{test?.testingTitle}}</label>
<form [formGroup]="testForm">
<div class="dropdown modelo-dropdown">
<label for="testCd" class="modelo-label">Testing</label>
<button class="btn btn-default dropdown-toggle" data-toggle="dropdown" role="button" id="testCd" aria-haspopup="true" aria-expanded="true">{{testForm.get('testCd').value}}</button>
<div class="dropdown-menu modelo-dropdown-menu" aria-labelledby="testCd">
<a class="dropdown-item" *ngFor="let tests of test?.trainData; let i = index" id="tests.name" (click)="changeDropdown(testForm.get('testCd'), tests.name)">{{tests.name}}</a>
</div>
</div>
<form [formGroup]="testForm2" (ngSubmit)="submitForm()">
<div class="row">
<div class="col-12 col-sm-4 group">
<input type="text" id="name" formControlName="name" class="modelo-text-input"
[ngClass]="{'ng-not-empty' : testForm2.get('name').value.length !== 0}">
<label for="name">Name</label>
</div>
</div>
<div class="row">
<div class="col-12 col-sm-4 group">
<input type="text" id="email" formControlName="email" class="modelo-text-input"
[ngClass]="{'ng-not-empty' : testForm2.get('email').value.length !== 0}">
<label for="email">Email</label>
</div>
</div>
<div class="row">
<div class="col-12 col-sm-4 group">
<input type="text" id="tel" formControlName="tel" class="modelo-text-input"
[ngClass]="{'ng-not-empty' : testForm2.get('tel').value.length !== 0}">
<label for="tel">Telephone #</label>
</div>
</div>
<div class="col-1 group generateButton">
<button class="btn btn-primary" type="submit">Submit Info</button>
</div>
</form>
My Question is, I'm have everything set up for a post and what I'm trying to do is post testForm2.value to the json but under "trainData":[{}] that's within the JSON. I'm able to do so if I just drop all other objects inside the json and have just the array after "customers":... What exactly am I missing? I'm actually confusing myself right now and I may be overthinking this by alot. The post I have currently in this code works if I have just the array after "customers":.... so instead of me passing object which is the testForm2.value what else do I need to do? I hope this makes sense.
You have some strange things in your code. First :
In you API
return this.http.get<Test[]>("http://localhost:3000/customers", {params}).pipe(map(res => res));
I think what you want to do here is : (the pipe is useless you dont use it and it's not an array)
return this.http.get<Test>("http://localhost:3000/customers",{params});
In your component you want to push the update trainData list
submitForm(){
const lastTrainData = this.test.trainData[this.test.trainData.length-1];
const newTrainData = this.testForm2.value;
newTrainData.id = lastTrainData.id + 1;
this.test.trainData.push(newTrainData);
this.TestService.postTests(this.test);
}

How to loop through nested JSON data

I am trying to loop through json data bellow, to so each element. I need to get down to the details data and then in side that loop through the f1,f2 into a div. I have tried using the index but that didn't work. Also I don't know how many f1,f2 there will be as it is returned from an api
JSON data
{
"data":[
{
"title": "test",
"image": "assets/imgs/test.png",
"date": "22/07/2018 - 19.00",
"location": "test",
"details": [
{
"f1":[
{
"FunctioName": "test",
"Time": "10:00:00"
}
],
"f2":[
{
"FunctioName": "test",
"Time": "11:00:00"
}
]
}
]
}
]
}
HTML
<div *ngFor="let item of card">
<div class="swiper-zoom-container">
<div class="out-card-box">
<h2>Date</h2>
<p>{{item.date}}</p>
<h2>Program</h2>
<div *ngFor="let details of item.details; let i = index">
</div>
</div>
</div>
</div>
TS
import { Component } from '#angular/core';
import { App } from 'ionic-angular';
import { DataService } from "../../services/data";
import { LoginPage } from "../login/login";
import { AngularFireAuth } from "angularfire2/auth";
import { Storage } from "#ionic/storage";
#Component({
selector: 'page-card',
templateUrl: 'card.html',
})
export class CardPage {
card:any;
constructor(private dataservice: DataService, private afAuth:AngularFireAuth, private app:App, private storage:Storage) {
this.dataservice.cardData().subscribe(
data => {
var jsonObj = JSON.parse(data["_body"]);
this.card = jsonObj.data;
console.log(jsonObj.data)
}
);
}
You can create an object which will hold the returned data from the api and you can just navigate the object values.
Example:
export class Class1 {
data: Class2[];
}
export class Class2 {
title: string;
image: string;
date: string;
location: string;
details: Class3[];
}
export class Class3 {
f1: Class4[];
f2: Class4[];
}
export class Class4 {
FunctioName: string;
Time: string
}
#Component({
selector: 'page-card',
templateUrl: 'card.html',
})
export class CardPage {
card:Class1;
constructor(private dataservice: DataService, private afAuth:AngularFireAuth, private app:App, private storage:Storage) {
this.dataservice.cardData().subscribe(
data => {
this.card = data;
}
);
}
then in your component template
<div *ngFor="let item of card.data">
<div class="swiper-zoom-container">
<div class="out-card-box">
<h2>Date</h2>
<p>{{item.date}}</p>
<h2>Program</h2>
<div *ngFor="let details of item.details; let i = index">
<!-- Print the remaining items here -->
</div>
</div>
</div>
</div>

No provider for ControlContainer and No provider for ControlContainer

I am working on an application using Angular2.
I am trying to use Reactive Forms in my application but I am running into some errors :
The first error is about NgControl as below:
No provider for NgControl ("
div class="col-md-8"
[ERROR ->]input class="form-control"
id="productNameId"
"): ProductEditComponent#16:24
The second error is about ControlContainer as below:
No provider for ControlContainer ("
div
[ERROR ->]div formArrayName="tags">
div class="row">
button cl"):
Htmm file is as below:
<div class="panel panel-primary">
<div class="panel-heading">
{{pageTitle}}
</div>
<div class="panel-body">
<form class="form-horizontal"
novalidate
(ngSubmit)="saveProduct()"
formGroup="productForm" >
<fieldset>
<div class="form-group"
[ngClass]="{'has-error': displayMessage.productName }">
<label class="col-md-2 control-label" for="productNameId">Product Name</label>
<div class="col-md-8">
<input class="form-control"
id="productNameId"
type="text"
placeholder="Name (required)"
formControlName="productName" />
<span class="help-block" *ngIf="displayMessage.productName">
{{displayMessage.productName}}
</span>
</div>
</div>
<div formArrayName="tags">
<div class="row">
<button class="col-md-offset-1 col-md-1 btn btn-default"
type="button"
(click)="addTag()">Add Tag
</button>
</div>
<div class="form-group"
*ngFor="let tag of tags.controls; let i=index" >
<label class="col-md-2 control-label" [attr.for]="i">Tag</label>
<div class="col-md-8">
<input class="form-control"
[id]="i"
type="text"
placeholder="Tag"
formControlName="i" />
</div>
</div>
</div>
<!--more piece of code here -->
My component file is as below:
import { Component, OnInit, AfterViewInit, OnDestroy, ViewChildren, ElementRef } from '#angular/core';
import { FormBuilder, FormGroup, FormControl, FormArray, Validators, FormControlName,NgForm } from '#angular/forms';
import { ActivatedRoute, Router } from '#angular/router';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/observable/fromEvent';
import 'rxjs/add/observable/merge';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import { IProduct } from './product';
import { ProductService } from './product.service';
import { NumberValidators } from '../shared/number.validator';
import { GenericValidator } from '../shared/generic-validator';
#Component({
templateUrl: './product-edit.component.html'
})
export class ProductEditComponent implements OnInit, AfterViewInit, OnDestroy {
#ViewChildren(FormControlName, { read: ElementRef }) formInputElements: ElementRef[];
pageTitle: string = 'Product Edit';
errorMessage: string;
productForm: FormGroup;
product: IProduct;
private sub: Subscription;
// Use with the generic validation message class
displayMessage: { [key: string]: string } = {};
private validationMessages: { [key: string]: { [key: string]: string } };
private genericValidator: GenericValidator;
get tags(): FormArray {
return <FormArray>this.productForm.get('tags');
}
constructor(private fb: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private productService: ProductService) {
// Defines all of the validation messages for the form.
// These could instead be retrieved from a file or database.
this.validationMessages = {
productName: {
required: 'Product name is required.',
minlength: 'Product name must be at least three characters.',
maxlength: 'Product name cannot exceed 50 characters.'
},
productCode: {
required: 'Product code is required.'
},
starRating: {
range: 'Rate the product between 1 (lowest) and 5 (highest).'
}
};
// Define an instance of the validator for use with this form,
// passing in this form's set of validation messages.
this.genericValidator = new GenericValidator(this.validationMessages);
}
ngOnInit(): void {
this.productForm = this.fb.group({
productName: ['', [Validators.required,
Validators.minLength(3),
Validators.maxLength(50)]],
productCode: ['', Validators.required],
starRating: ['', NumberValidators.range(1, 5)],
tags: this.fb.array([]),
description: ''
});
// Read the product Id from the route parameter
this.sub = this.route.params.subscribe(
params => {
let id = +params['id'];
this.getProduct(id);
}
);
}
ngOnDestroy(): void {
this.sub.unsubscribe();
}
ngAfterViewInit(): void {
// Watch for the blur event from any input element on the form.
let controlBlurs: Observable<any>[] = this.formInputElements
.map((formControl: ElementRef) => Observable.fromEvent(formControl.nativeElement, 'blur'));
// Merge the blur event observable with the valueChanges observable
Observable.merge(this.productForm.valueChanges, ...controlBlurs).debounceTime(800).subscribe(value => {
this.displayMessage = this.genericValidator.processMessages(this.productForm);
});
}
addTag(): void {
this.tags.push(new FormControl());
}
getProduct(id: number): void {
this.productService.getProduct(id)
.subscribe(
(product: IProduct) => this.onProductRetrieved(product),
(error: any) => this.errorMessage = <any>error
);
}
onProductRetrieved(product: IProduct): void {
if (this.productForm) {
this.productForm.reset();
}
this.product = product;
if (this.product.id === 0) {
this.pageTitle = 'Add Product';
} else {
this.pageTitle = `Edit Product: ${this.product.productName}`;
}
// Update the data on the form
this.productForm.patchValue({
productName: this.product.productName,
productCode: this.product.productCode,
starRating: this.product.starRating,
description: this.product.description
});
this.productForm.setControl('tags', this.fb.array(this.product.tags || []));
}
deleteProduct(): void {
if (this.product.id === 0) {
// Don't delete, it was never saved.
this.onSaveComplete();
} else {
if (confirm(`Really delete the product: ${this.product.productName}?`)) {
this.productService.deleteProduct(this.product.id)
.subscribe(
() => this.onSaveComplete(),
(error: any) => this.errorMessage = <any>error
);
}
}
}
saveProduct(): void {
if (this.productForm.dirty && this.productForm.valid) {
// Copy the form values over the product object values
let p = Object.assign({}, this.product, this.productForm.value);
this.productService.saveProduct(p)
.subscribe(
() => this.onSaveComplete(),
(error: any) => this.errorMessage = <any>error
);
} else if (!this.productForm.dirty) {
this.onSaveComplete();
}
}
onSaveComplete(): void {
// Reset the form to clear the flags
this.productForm.reset();
this.router.navigate(['/products']);
}
}
I am trying to solve this problem for more than 2 days but I still do not have a solution. I have seen many other answers in stackoverflow but none of them is solving my problem.
Import both Forms Module and ReactiveFormsModule from #angular/forms in the file app.module.ts