Determining Cost Using Quantity and Option Changes in Angular 4

Task
In the shopping cart, there is a list of items with options, quantities, and prices. The goal is to calculate the total price based on any changes in the quantity and option of an item.

Investigation I included [(ngModel)] for 2-way data binding, but for some reason, the page keeps loading and then crashes without any error message. Removing the ngModel attribute allows the page to load successfully.

<span class="price col-1 pull-right" >{{ orderType*price}}</span>
<div class="qty" style="margin:0;">
     <span class="spinner">
        <span class="sub">-</span>
        <input type="number" id="qty" name="qty" min="1" max="100" 
               value="1" class="qty-spinner" [(ngModel)]="quantity" />
        <span class="add">+</span>
     </span>
 </div>
 <div class="type">
     <label class="radio inline" *ngFor="let option of item.options; let k = index"> 
     <input id="{{'toggle-half-'+item.id+'-'+j}}" type="radio" 
            name="{{'option-toggle-'+item.id+'-'+j}}" [value]="option.value" 
            [checked]='k===0' [(ngModel)]="orderType" />
     <span>{{option.title}} </span> 
     </label>
 </div>

TypeScript Implementation

quantity:number;
orderType:number;
price:number;

constructor() {
    this.quantity = 1;
    this.price = 0;
}

Controls Utilized
1) Number Control with input type number for quantity input.
2) Radio Controls for Options [Half/Full]
3) Span element for displaying the calculated price.

Desired Outcome
The current price, set at 0, should update when either the quantity or option is modified.
Example values for option [Half] = 10
Example values for option [Full] = 20

Please provide guidance on how to execute this. Is the above logic and implementation correct?

Thank you in advance

Answer №1

The variable option is currently being used in the ngFor directive. Refer to line:

<label class="radio inline" *ngFor="let option of item.options; let k = index">

Please use a different variable for the ngModel, for example:

<input id="{{'toggle-half-'+item.id+'-'+j}}"  
       type="radio" 
       name="{{'option-toggle-'+item.id+'-'+j}}" 
       [value]="option.value"
       [(ngModel)]="selectedOption" />

Refer to the examples in the documentation;

EDIT

Additionally, you are binding the checked attribute while using an ngModel. Instead of that, initialize the ngModel with the desired value, like this:

selectedOption = item.options[0].value

Answer №2

Update: After examining the provided code sample from jkris' response, it appears that utilizing value for radio inputs is appropriate. Nevertheless, my hunch persists that combining checked with [(ngModel)] may trigger an update loop.


I observed that you are linking checked alongside the NgModel binding. Have you tried removing it to see if the desired functionality remains intact without causing any crashes?

<input type="number" class="qty-spinner" min="1" max="100" 
       name="quantity" [(ngModel)]="quantity" />


<input type="radio" 
       [value]="option.value" name="option" [(ngModel)]="option" />

If not, an alternative approach could involve using [checked] and (click) (or a similar event) bindings instead of NgModel.

Answer №3

Uncertain as to the reason for the crash, but if in your position, I would consider altering the constructor

constructor() {
    this.quantity = 1;
    this.price = 0;
}

Instead of this, I suggest utilizing ngInit since it allows for two-way binding.

     import { OnInit } from '@angular/core';

        export class myClas implements OnInit {

        ngOnInit() {
            this.quantity = 1;
            this.price = 0;
        }

    }

Furthermore, ensure that the radio button and input type number actually return values of type number. It might be advisable to initially use strings and then convert them to the desired number type afterward. Alternatively, using a pipe could also be beneficial. Incorrect type conversion can sometimes lead to performance issues. Therefore, why not try:

quantity:string;
orderType:string;
price:string;

initially and then perform the number conversions later on?

Answer №4

The problem has been successfully resolved. I had placed the code snippet within a div tag that included a *ngFor directive, iterating through a list of items.

Problem
To split the list of items into 2 columns using "div.col-md-6", I created a function that returned two arrays, each containing a set of items. The intention was to iterate through each array and display the items in separate columns.

I couldn't figure out why there was an issue only when I added the ngModel tag, which shouldn't have caused any problems. Nonetheless, removing the splitting function solved the issue for me.

Thank you to everyone for your assistance and support.

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

Combining PHP, Javascript, and Ajax all in one powerful code snippet

Would it be considered poor coding practice to combine PHP, JavaScript, and AJAX in the same block of code? For example: <?php $randNum = rand(1,10) if ($randNum <= 5) { echo "Enemy got the jump on you! <script> enemyTurn() </script& ...

Enhancing the validation of multiple selects using jQuery

Here is what I have accomplished so far: JSFIDDLE My current goal is to: add the class "invalid" to the <select> if it was not selected in its respective row remove the "invalid" class if all 3 selects in the row are selected automatically submit ...

Troubleshooting: Vue.js custom select element not responding to blur event

Unique Scenario A custom autocomplete select component has been created that not only autocompletes but also allows for adding a new value if the result is not found. This functionality was discovered to be missing in the vue-select module. Explore the C ...

MDX is revolutionizing Next app routing with the introduction of 'use client' functionality

After setting up MDX with Next.js 14, I encountered an error when navigating to the mdx page: Error: createContext only works in Client Components. Add the "use client" directive at the top of the file to use it. The file mdx-components.tsx is ...

Displaying the countdown of days and hours until a specific date is just a matter of using

Currently, I am tackling a project that necessitates a specific text response related to a date object. "1 day 7 hours away" --- This format is crucial; alternatives such as "31 hours away" or "1 day away" will not suffice. -- For language switching purpo ...

Creating a large and spacious modal in Angular using ngx-bootstrap

I need help with resizing the ngx-modal to cover a large area of the screen. Currently, I am trying to make it so that when something is clicked, the modal should overlay an 80% width grid on a full desktop screen. Despite my attempts at using .modal-xl an ...

Retrieve data from an ASP.NET Web API endpoint utilizing AngularJS for seamless file extraction

In my project using Angular JS, I have an anchor tag (<a>) that triggers an HTTP request to a WebAPI method. This method returns a file. Now, my goal is to ensure that the file is downloaded to the user's device once the request is successful. ...

Come back to Angular 2 on your return function

Having a problem with an asynchronous function. There is a service that retrieves data from a Firebase database. One of the functions returns a value: historialDeConsumi() { this.item = this.af.database.object('/users/' + this.uid + '/a ...

Concealing tooltip when button is clicked using jQuery

I am facing an issue where the tooltip does not hide on button click. Below is the code for the button in question: <button class="btn btn-outline-inverse ajax_addtocart additems ...

hybrid application combining AngularJS with Angular 17 and above versions

I have been attempting to set up a hybrid environment with both AngularJS and Angular 1.7+ running side by side. I diligently followed all the guidelines and even created a custom webpack configuration to bundle my AngularJS and Angular files together. The ...

Storing information on the webpage when it is refreshed

My goal is to maintain the order of the data in the target ordered list even after a page refresh, achieved through jQuery prepend on document ready. Here's the code snippet: // when a refresh event occurs window.onbeforeunload = function(event){ ...

Sending the ID of a mapped button to a component

I need help with my React mapping function that displays a series of cards, each with its own button to open up a dialog box. Right now, I'm struggling to pass the unique ID from each object to the correct dialog box. Instead, all IDs are being passed ...

What could be causing this JavaScript code not to run?

Help needed! I'm a student struggling to diagnose the issue in my code. Whenever I click the buttons, nothing happens at all. I've tried debugging by isolating each function, but still can't seem to figure it out. I've searched through ...

How to change a string from utf-8 to iso-8859-1 using Javascript

Although it may seem unpleasant, it is essential. I am facing an issue with a HTML form on my website that uses utf-8 charset but is sent to a server operating with iso-8859-1 charset. The problem arises when the server fails to interpret characters commo ...

Convert a single object into a JSON string representation on each line

Can you convert the following data into the desired format through stringification? Data: let result = JSON.stringify([ { "Color": "Red", "Type":"Fast" }, { "Color": "Blue&quo ...

arrange the elements in a specified sequence

I am trying to sort an array in a specific order var customOrder = { "1st Presentation / Meeting": 0, "Follow-On Meetings": 1, "Hold\/Uncategorized": 2, "MGL": 3, "PGL": 4, "BGL": 5, "RGL": 6, "SGL": 7, "Uncategorized Leads": 8, ...

Understanding and parsing JSON with object pointers

Is it possible to deserialize a JSON in typescript that contains references to objects already existing within it? For instance, consider a scenario where there is a grandparent "Papa" connected to two parents "Dad" and "Mom", who have two children togeth ...

What could be the reason for the validation failure?

companyprofile.html <form #f="ngForm" name="companyProfileForm" ng-submit="companyFrmSave(objCS, objCSCurrency)" novalidate=""> <div class="row form-group"> <div class="col-md-12" > ...

What are the benefits of incorporating NgRx in Angular, even when data is consistently synchronized through two-way data binding?

NgRx, analogous to Redux in React, is a tool used for state management in Angular. While state management can become convoluted in React projects, Angular typically avoids this issue thanks to its two-way data binding synchronization. Interestingly, many ...

I possess a solitary div element that requires dynamic replication

I have a single container and an unspecified number of rows of data. I want to display this data on HTML cards that are generated dynamically based on the number of rows. For example, if there are 10 rows of data, I need to create 10 card elements with ea ...