Angular商品详情页点击数量增减按钮后显示NaN问题求助
Hey there, let's get that quantity showing correctly instead of NaN! I looked through your code and found the root cause right away.
The Problem
In your Product-Details.Component.ts file, the way you declared the quantity property is incorrect:
quantity: 1;
This is a TypeScript type annotation (you're telling TypeScript that quantity must be the literal value 1), but you didn't actually assign an initial value to it. That means quantity starts as undefined by default. When you try to increment/decrement it (this.quantity++ or this.quantity--), you're performing arithmetic on undefined—which results in NaN.
The Fix
Update the quantity declaration to assign an initial value instead of just a type constraint. You have two valid options:
- Simple assignment (TypeScript will infer the type as
numberautomatically):
quantity = 1;
- Explicit type + assignment (great for clarity if you want to enforce the type explicitly):
quantity: number = 1;
Why This Works
By assigning 1 as the initial value, quantity starts as a valid number. Now when you click the plus/minus buttons, the increment/decrement operations will work on a number instead of undefined, so the quantity will update correctly and show the expected number instead of NaN.
Once you make this change, your quantity display should work as intended—loading with 1, and updating properly when you click the icons.
内容的提问来源于stack exchange,提问作者Lanre Afeez

