Oops! There seems to be an issue where the 'title' property is being accessed from an undefined source

I've been struggling with this code block for the past few days, and even when attempting to initialize it as an object, I encounter errors.

Here is my restaurantForm.ts file

import { Component, OnInit } from '@angular/core';
import {RestaurantService} from '../../restaurant.service';
import {ProductService} from '../../product.service';
import {ActivatedRoute, Router} from '@angular/router';
import 'rxjs/add/operator/take';
import {Product} from '../../model/product';

@Component({
  selector: 'app-product-form',
  templateUrl: './restaurant-form.component.html',
  styleUrls: ['./restaurant-form.component.css']
})
export class RestaurantFormComponent implements OnInit {
  restaurants$;
  id;
  product: Product;
  constructor(private restaurantService: RestaurantService,
              private productService: ProductService,
              private route: ActivatedRoute,
              private router: Router) {
    this.restaurants$ = this.restaurantService.getAll();
    this.id = this.route.snapshot.paramMap.get('id');
    if (this.id) {
      this.productService.get(this.id).take(1).subscribe(p => this.product = p);
    }
   this.product = new Product();
  }
  save(product) {
    if (this.id) {
      this.productService.update(this.id, product);
    } else {
      this.productService.create(product);
    }
    this.router.navigate(['/admin/restaurants']);
  }
  delete() {
    if (!confirm('Are you sure you want to delete this product?')) { return ; }
      this.productService.delete(this.id);
      this.router.navigate(['/admin/restaurants']);
  }

  ngOnInit() {
  }

}

This is my product model

export interface Product {
  $key: string;
  title: string;
  price: number;
  restaurant: string;
  imageUrl: string;

}

Here is my restaurantForm.html

<div class="container">
  <div class="row">
    <div class="col-md-6">
      <form #f="ngForm" (ngSubmit)="save(f)">
        <div class="form-group">
          <label for="title">Title</label>
          <input #title="ngModel" [(ngModel)]="product.title" name="title" id="title" type="text" class="form-control" required>
          <div class="alert-danger alert" *ngIf="title.touched && title.invalid">
            Title is required.
          </div>
        </div>
        <div class="form-group">
          <label for="price">Delivery Price</label>
          <div class="input-group">
            <span class="input-group-addon">₦</span>
            <input #price="ngModel" [(ngModel)]="product.price" name="price" id="price"
                   type="number" class="form-control" required [min]="0">
          </div>
          <div class="alert alert-danger" *ngIf="price.touched && price.invalid">
            <div *ngIf="price.errors.required">
              Delivery Price is required
            </div>
            <div *ngIf="price.errors.min">
              Delivery Price should be 0 or higher.
            </div>
          </div>
        </div>
        <div class="form-group">
          <label for="restaurant">Restaurant</label>
          <select #restaurant="ngModel" [(ngModel)]="product.restaurant" name="restaurant" id="restaurant" class="form-control" required>
            <option value=""></option>
            <option *ngFor="let r of restaurants$ | async" [value]="r.$key">
              {{ r.name }}
            </option>
          </select>
          <div class="alert alert-danger" *ngIf="restaurant.touched && restaurant.invalid">
            Please select a restaurant.
          </div>
        </div>
        <div class="form-group">
          <label for="imageUrl">Image Url</label>
          <input #imageUrl="ngModel" [(ngModel)]="product.imageUrl" name="imageUrl"
                 id="imageUrl" type="text" class="form-control" required url>
          <div class="alert alert-danger" *ngIf="imageUrl.touched && imageUrl.invalid">
            <div *ngIf="imageUrl.errors.required">Image Url is required.</div>
            <div *ngIf="imageUrl.errors.url">Please enter a valid Url.</div>
          </div>
        </div>
        <button  class="btn btn-primary">Save</button>
        <button type="button" (click)="delete()" class="btn btn-danger">Delete</button>
      </form>
    </div>
    <div class="col-md-6">
     <app-product-card [product]="product" [showActions]="false"></app-product-card>
    </div>
  </div>
 </div>

The same issues persist with price, $key, restaurant and imageUrl. I appreciate any help. Although I have explored solutions suggesting the use of the Elvis Operator e.g 'product?.title', this method has not proven successful yet.

Answer №1

When the product is not defined, it is necessary to initialize it with an empty object in either the constructor or ngOnInit.

NEW INFO:

To ensure that the Product is correctly declared within the component, use the following code snippet:

const product : Produce = {  $key: "", title: "",price:0,restuarant :"" ,imageurl:"" };

Answer №2

Upon initialization of the template, the product is initially undefined and will remain so until a response is received from the API. Ensure to add a conditional check within the template when binding object properties, as well as for other attributes such as price.

<input *ngIf="product.title" #title="ngModel" [(ngModel)]="product.title" name="title" id="title" type="text" class="form-control" required>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with Vue 3 where radio input remains unchecked after being clicked

I'm currently facing an issue with radio buttons for answers in my questions. Whenever I click on an answer, the radio input does not stay checked and I am unable to disable the other options. My front-end is developed using Vue 3 and the back-end wit ...

Having trouble getting collision events to trigger in ThreeJS when using the PhysiJS physics engine?

When an object falls and collides with the ground, an alert box should pop up displaying the message "Box just hit the ground". However, there seems to be an issue as the alert box is not being created upon collision. Additionally, no relevant JavaScript ...

Leveraging conditions to retrieve information in the desired format from MongoDb

Here is an example of what the sample documents look like { userId: 1, totalGames: 10, winStats: 4, lostStats: 6, g1Stats: { totalGames: 4, winStats: 1, lostStats: 3, }, g2Stats: { totalGames: 5, wi ...

Having trouble with an Ajax request in jQuery

Need some help with the code below - I can't seem to get the success or error event to fire. Even though the server returns a 200 OK response with the required data. Any assistance would be greatly appreciated! $('body').on('click&apos ...

Receiving an ambiguous message from the meteor subscriptions

New to using Meteor, I am trying to create a registration form with Meteor. I am facing some challenges with the `findOne` and `subscribe/publish` functions. Here is my `collection.js` file: User_Customer = new Meteor.Collection("USER_CUSTOMER"); Custome ...

"AngularJS Bi-Directional Data Binding Issue: Unexpected 'Undefined

Recently, I've been tackling a project that involves using a directive. Initially, everything was smooth sailing as I had my directive set up to bind to ngModel. However, I hit a roadblock when I needed to bind multiple values. Upon making the necessa ...

The installation of @angular/router seems to have encountered an error

I am attempting to update my @angular/router dependency from version 2.0.0 to 3.0.0-alpha.7. I have included it in my package.json file. { "name": "angular2-quickstart", "version": "1.0.0", "scripts": { "start": "tsc && concurrently &bs ...

Why is my webpage attempting to refresh every time I send an AJAX request?

I have been struggling to send a form using AJAX, but no matter how many times I use e.preventDefault(), the page still tries to reload. Here is my HTML: <form action="/user/changeProfileData" id="edit-profile_form" method="post"> <ul class=& ...

The issue with MUI material autocomplete not functioning properly when onBlur is triggered

Although the onFocus parameter is working fine in material autocomplete, I'm facing an issue with the onBlur parameter. Can someone explain why this might be happening and provide a correct solution to implement it? <Autocomplete onBlur={() ...

Tips for designing a masonry grid with Bootstrap 4

I'm attempting to achieve a specific layout using Bootstrap 4, JavaScript, CSS, and HTML. I have not been able to find something similar on Stack Overflow, but I did come across the Bootstrap 4 Cards documentation. However, I am unsure if this is the ...

Fade out a background image using jQuery

I am currently working on customizing a jQuery slider similar to NivoSlider. I want to replace the default images with my own controls. Here is what I have in HTML: <div id="slider" class="nivoSlider"> <img src="img/slider/start1.jpg" alt="" ...

Using jQuery to send LocalStorage data to an email address with the help of PHP

Currently, I am in the process of developing a basic eCommerce/checkout system. My goal is to utilize localStorage data and transfer it to PHP using jQuery or any other method that is convenient. However, when I attempted to send the email, I only received ...

How to incorporate Mixin in your Nuxt template

I'm having trouble utilizing the mixin function in my template. Although Vue documentation states that mixins and components are merged, I am unable to call the function. getImage is not a function Mixin export default { data() { return { ...

Tips for transferring an item to PHP

I am facing a challenge in sending data from the client side (javascript) to the server (php) using ajax. My object structure is as follows: sinfo={ topic_title:title, topic_id: tid, section_name:section_name, ...

Unable to include checkout and clear cart buttons in popover within bootstrap 5

I am currently working with BootStrap version 5.0.0 beta-2 and facing an issue when attempting to dynamically add a button within my popover. I have ensured that the scripts are included in the following order: <script src="https://ajax.googleapis. ...

Angular often uses the JavaScript pattern for development

After completing an AngularJS tutorial on http://www.tutorialspoint.com/angularjs/angularjs_services.htm, I found myself puzzled by the method used in the CalcService service. It seemed unclear whether Angular was using revealing prototype or a different ...

Execute an xmlhttprequest and then redirect to a different URL

I'm a beginner when it comes to AJAX and JavaScript. My goal is to first show a confirmation box, then send an XMLHttpRequest if confirmed. After that, I want to redirect the user to a new page. Below is my current code: <script type="text/javascr ...

The use of custom loaders alongside ts-node allows for more flexibility

Is it possible to utilize ts-node with a custom loader? The documentation only mentions enabling esm compatibility. ts-node --esm my-file.ts I am attempting to implement a custom loader for testing an ESM module, but I prefer not to rely on node for compi ...

What is the best way to send a selected value to a different function in order to retrieve data from a JSON file based on that

I have been working on writing HTML and JavaScript code to extract data from a JSON file. Here is a snippet of my HTML code: <div class="section"> <div class="sectionTitle"> <h3>Configuration</h3> </div> &l ...

Utilizing Ajax to retrieve an array of input textboxes and showcase the outcome within a div container

This is the form that I have designed for displaying information: <form name='foodlist' action='checkout' method='POST'> <table> <tr> <td>Product Name</td> <td>Price</t ...