The product information is showing as NaN instead of the quantity amount

I'm currently facing a complex issue with my Product Detail page. The page is designed to display product information, allow users to increment and decrement the quantity of a product, but when I click on the icons for increasing or decreasing the quantity, instead of showing the actual quantity it displays "NaN". There are no errors in my code editor, so I'm struggling to figure out what's causing this issue. I've been working on this problem all day and would greatly appreciate any help in pinpointing where I've gone wrong. Thank you in advance.

Product-Details.Component.ts

import { Component, OnInit } from '@angular/core';
import { IProduct } from 'src/app/shared/models/product';
import { ShopService } from '../shop.service';
import { ActivatedRoute } from '@angular/router';
import { BreadcrumbService } from 'xng-breadcrumb';
import { BasketService } from 'src/app/basket/basket.service';

@Component({
  selector: 'app-product-details',
  templateUrl: './product-details.component.html',
  styleUrls: ['./product-details.component.scss']
})
export class ProductDetailsComponent implements OnInit {
  product: IProduct;
  quantity: 1;

  constructor(private shopService: ShopService, private activateRoute: ActivatedRoute, 
    private bcService: BreadcrumbService, private basketService:BasketService) { 
      this.bcService.set('@productDetails', ''); 
    }

  ngOnInit(): void {
    this.loadProduct();     
  }

  addItemToBasket() {
    this.basketService.addItemToBasket(this.product, this.quantity);
  }

  incrementQuantity() {
    this.quantity++;
  }

  decrementQuantity() {
    if(this.quantity > 1) {
      this.quantity--;
    }
  }

  loadProduct() {
    this.shopService.getProduct(+this.activateRoute.snapshot.paramMap.get('id')!).subscribe(product => {
      this.product = product;
      this.bcService.set('@productDetails', product.name)
    }, error => {
      console.log(error);
    });
  }

}

Product-Details.Component.html

<div class="container mt-5">

    <div class="row" *ngIf="product">
        <div class="col-6">
            <img src="{{product.pictureUrl}}" alt="{{product.name}}" class="img-fluid w-100">
        </div>

        <div class="col-6">
            <h3>{{product.name}}</h3>
            <p style="font-size: 2em;">{{product.price | currency}}</p>
            <div class="d-flex justify-content-start align-items-center">
                <i (click)="decrementQuantity()" class="fa fa-minus-circle text-warning mr-2" style="cursor: pointer; font-size: 2em;"></i>
                <span class="font-weight-bold" style="font-size: 1.5em;">{{quantity}}</span>
                <i (click)="incrementQuantity()" class="fa fa-plus-circle text-warning mx-2" style="cursor: pointer; font-size: 2em;"></i>
                <button (click)="addItemToBasket()" class="btn btn-outline-primary btn-lg ml-4">Add to Cart</button>
            </div>
        </div>

        <div class="row mt-5">
            <div class="col-12 ml-3">
                <h4>Description</h4>
                <p>{{product.description}}</p>
            </div>
        </div>
    </div>


</div>

Answer №1

As per the information provided in TypeScript - Variables,

In TypeScript, when declaring a variable, you need to specify its type by using a colon (:) after the variable name.

If you include a colon (:) after the variable, you are required to indicate its type.

quantity: number = 1;

Alternatively,

You can directly assign a numeric value to the variable which will automatically be considered as a number type.

quantity = 1;

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

Allowing HTML attributes in reusable components with Vue TSX: A guide on informing Typescript

Imagine I have a custom input component: import { defineComponent } from "@vue/runtime-core" export default defineComponent({ inheritAttrs: false, setup(props, { attrs }) { return () => ( <div> ...

What is the process for defining the default landing page route in Angular routing?

My application currently has only one route, and I want it to start with the URL http://localhost:4200/specialtyQ. However, my application is not loading properly. The code snippet below is what I am using to try to achieve this. How can I correct the URL ...

What is the best way to dynamically add fields to every object in an array of Firestore documents using RxJS?

Trying to solve a challenging RxJS issue here. In my Angular service class, I initially had a method that fetched data from the Firebase Firestore database like this: async getAllEmployees() { return <Observable<User[]>> this.firestore.co ...

Tips for extracting specific JSON response data from an array in TypeScript

I have an array named ReservationResponse, which represents a successful response retrieved from an API call. The code snippet below demonstrates how it is fetched: const ReservationResponse = await this.service.getReservation(this.username.value); The st ...

Navigating URLs to index.html for localized Angular application within lighttpd server - a guide

When deploying an Angular application to a lighttpd server, if a user is browsing example.com/product/12 and sends the link to someone else, they may encounter a 404 error without proper URL rewriting. In this scenario: localized versions are stored in s ...

How to Activate Animation Post-Page Load in Angular 8, Overcoming ExpressionChangedAfterItHasBeenCheckedError

Trying to solve a crucial question concerning animating an element after the page has fully loaded. Despite extensive research, I have yet to find a simple and efficient solution. Can anyone offer some advice? Once the mobile page is loaded, I want the log ...

Learn the technique of breaking down an object in React that contains unique characters in its keys

When the backend returns an object and I need to handle a specific key differently, how can I split up the object? useEffect(() => { const tempUserShortId = getTempUserShortId() axios({ method: 'get', url: `questionList ...

Issue: The data type '[number] | [number, number, number, number]' cannot be matched with the type '[number]'

Upon upgrading from angular 5.1 to 6.1, I started encountering errors in my code, such as the one below: Error: ngc compilation failed: components/forms/utils.ts(5,3): error TS2322: Type '[number] | [number, number, number, number]' is not ...

Exploring the power of Typescript and Map in Node.js applications

I am feeling a little perplexed about implementing Map in my nodejs project. In order to utilize Map, I need to change the compile target to ES6. However, doing so results in outputted js files that contain ES6 imports which causes issues with node. Is t ...

Encountered an error while setting up a new Angular project: Installation of

Angular CLI: 8.3.8 Node: 10.16.3 OS: darwin x64 Angular: ... Package Version ------------------------------------------------------ @angular-devkit/architect 0.803.8 @angular-devkit/core 8.3.8 @angular-devkit/schematics ...

Guide to streaming a .m4v video using NodeJS

My objective is to send videos stored as local files on the server to the client. Unlike a static 'videos' folder, I need to handle dynamic videos that are only temporarily available. Is there a way to retrieve the .m4v video file from the serve ...

What is the reason behind the triggering of actions by ngrx entity selectors?

I'm currently in the process of learning NgRx, but I'm struggling to comprehend why entity selectors would trigger actions. Despite my efforts to find an explanation, I have come up short. It's possible that I may be missing some fundamental ...

Display array elements in a PDF document using pdfmake

Upon reaching the final page of my Angular project, I have an array filled with data retrieved from a database. How can I utilize pdfmake to import this data into a PDF file? My goal is to display a table where the first column shows interv.code and the ...

What steps can I take to resolve the issues with these typescript errors?

An issue arises with type 'string' as it does not meet the constraint 'unknown[]': const query = db.prepareQuery<string>( TS2707 [ERROR]: The generic type 'RouterContext<R, P, S>' needs to have between 1 an ...

Struggling with implementing map() inside another map() within the render() method in React TypeScript

I am looking to display messages and their corresponding replies in a React application using TypeScript. The messages are stored in one array within the state, while the replies are stored in a separate array. This is my current code which is not renderi ...

require the ability to dynamically adjust the header based on the content

I am using ag-grid-polymer and I need to adjust the header content so that user-entered text fits within the column size without being cut off by ellipses. .ag-theme-material .ag-header-cell-label .ag-header-cell-text { overflow: hidden; text-ov ...

Ways to display only a specific color in an image

Looking to work with an image that contains predefined color blocks? Take this example picture as reference: https://i.sstatic.net/QlwvY.png Is there a method to display only certain colored areas while keeping the rest transparent? Note that no edge pat ...

Loading and unloading an Angular 6 component

One challenge I'm facing involves creating an image modal that appears when an image is clicked. Currently, I have it set up so that the child component loads upon clicking the image. However, the issue is that it can only be clicked once and then dis ...

Error during Angular AOT compilation: The 'length' property is not available on the 'AbstractControl' type

I'm facing an issue with my app where I am trying to implement AOT for faster loading times. However, I am running into a compilation error when using ngc and AOT settings, specifically related to validating the FormA. In my TypeScript code, I have a ...

React Conditional State Setting

I have created a component that dynamically changes its background color based on the rating of a school. According to the specifications, if the school's rating falls between 1 and 3, the background color should be orange. For ratings between 4 and ...