Search code examples
angularangular4-forms

Angular 4 Cannot read property 'product_name' of undefined


I want to edit a product and show the details before update the product. I've developed a form and the related components and service however, I got an error message ERROR TypeError: Cannot read property 'product_name' of undefined in my angular 4 app. I wrote the following in "update-product.component.html:

<div class="container">
  <form [formGroup]="productUpdateForm" (ngSubmit)="updateproduct()" class="form-signin" novalidate
        [class.was-validated]="productUpdateForm.invalid && (productUpdateForm.dirty || productUpdateForm.touched)">
    <h2 class="form-signin-heading text-center">Update Product</h2>

   <div class="alert alert-danger" *ngIf="dataInvalid">
      <p *ngFor="let error of formErrors">{{ error }}</p>
    </div>
    <div class="form-group">
      <label class="sr-only">Product Name</label>
      <input type="text" formControlName="product_name" class="form-control" [class.is-invalid]="dataInvalid"
             placeholder="Enter Name" required [(ngModel)] = "data.product_name">
      <div class="invalid-feedback">
        Name is required.
      </div>
    </div>
    <button class="btn btn-lg btn-primary btn-block" type="submit" [disabled]="productUpdateForm.invalid" *ngIf="!formSubmitting">Update</button>
    <button class="btn btn-lg btn-primary btn-block" type="button" [disabled]="formSubmitting" *ngIf="formSubmitting">Updating...</button>
  </form>
</div>

And my update-product.component.ts is as follows:

import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {Router, RouterModule, ActivatedRoute} from '@angular/router';
import {HttpErrorResponse} from '@angular/common/http';
import { HttpClient , HttpHeaders }  from '@angular/common/http';
import { UpdateProductService } from './update-product.service';


@Component({
  selector: 'app-update-product',
  templateUrl: './update-product.component.html',
  styleUrls: ['./update-product.component.scss']
})
export class UpdateProductComponent implements OnInit {

  productUpdateForm: FormGroup;
  dataInvalid = false;
  formErrors = [];
  formSubmitting = false;
  id:number;

  constructor(private UpdateProductService: UpdateProductService, private route: ActivatedRoute, private fb: FormBuilder) { 
  this.createForm();
  }

    createForm(){
    this.productUpdateForm = this.fb.group({
      product_name: ['', Validators.required],
      description: ['', [Validators.required, Validators.maxLength(300)]]
    });
  }
   ngOnInit() {
   this.route.params.subscribe(params => {
      this.id = params['id'];
    });
    this.UpdateProductService.getProduct(this.id)
      .subscribe(data => {
        console.log(data);
        this.data = data;
      } 
  }
}

Please note, the data are showing properly in the input box however, at console, I got the above error.


Solution

  • You haven't declared data in your component.

        this.UpdateProductService.getProduct(this.id)
          .subscribe(data => {
            console.log(data);
            this.data = data;  // there is no variable data in your component
          } 
      }
    

    You need to declare it before using it.

    export class UpdateProductComponent implements OnInit {
    
      data:any="";
    

    Since you havent declared it and using product_name property of data in your html, it is throwing this error.