When I get the product_price it returns "Unsupported value type" as a result of the function below but I need for it to be a number. I tried this.product_price = parseFloat(this.product_price); but that returns the error: Argument of type 'number' is not assignable to parameter of type 'string'. How do I cast product_price as a number?
In my HTML:
- <div>{{ totalPrice }}</div>
- <ul *ngFor="let product of products">
- <li>
- <div>{{product.price }}</div>
- <button type="submit" class="btnAddAction" (click)="onSubmit( [product.price] )">Add to Cart</button>
- </li>
- </ul>
The HTML is getting the products from the database which was created with this JSON:
- {
- "products": [
- {
- "price": 20.50,
- },
- {
- "price": 20.50,
- },
- {
- "price": 12.75,
- }
- ]
- }
In my controller typescript file:
- get totalPrice() {
- if (typeof this.product_price === "string") {
- return "string";
- }
- if (typeof this.product_price === "number") {
- return "number";
- } else {
- throw Error("Unsupported value type")
- }
- }
- product_price: number;
-
- onSubmit(product_price){
- product_price = parseFloat(product_price);
- const data = {
- product_price
- };
- this.items.push(data);
- localStorage.setItem('items', JSON.stringify(this.items));
- }