简体   繁体   中英

How to sum multiple values from a multi-select drop down in Angular

I am creating a menu where you can select multiple additions and I am trying to sum the values together so I can display the total price in HTML. I have used [(ngModel)] to capture the first value selected but want to add the other values selected to have the total price. Instead of a total i'm getting NaN .

Any help would be appreciated.

Here is my HTML:

<div
  *ngIf="item.name === 'Ultimate Sirloin Nachos' || item.itemType === 'food'"
>
  <div class="form-group">
    <mat-form-field appearance="fill">
      <mat-label>Add Ons</mat-label>
      <mat-select
        [formControl]="addOns"
        [(ngModel)]="selectedAddOns"
        (ngModelChange)="updatePrice($event)"
        multiple
      >
        <mat-option *ngFor="let addOn of addOnList" [value]="addOn.addOnPrice"
          >{{addOn.addOnName}} + ${{addOn.addOnPrice}}
        </mat-option>
      </mat-select>
    </mat-form-field>
    <p><span>price: </span><b>{{+selectedAddOns}}</b></p>
    <p>{{selectedAddOns}}</p>
    <div class="form-outline">
      <mat-form-field appearance="fill">
        <mat-label>Subs:</mat-label>
        <textarea matInput placeholder="Ex. No tomato...etc."></textarea>
      </mat-form-field>
    </div>
  </div>
</div>

Here is how I have my typescript file set up.

selectedAddOns = 0;

selectedAddOnPrice = 0;

addtoOrder: Item;
ngOnInit(): void {
  this.getMenuItem();
}
// Gets menu item selected and pushes it to the detail page
getMenuItem(): void {
  const name = this.route.snapshot.paramMap.get("name");
  this.menuService
    .getMenuItemDetail(name)
    .subscribe((items) => (this.item = items));
}

updatePrice(event: number) {
  this.selectedAddOnPrice += event;
}

Couple of things:

  1. in your typescript file it looks like you copy/pasted your code twice, which is confusing.

  2. you have (ngModelChange)="updatePrice($event)" which is sending an "event" and not a number, where as your updatePrice() function is treating it as a number. That is likely your problem.

More likely what you need to do is have an array of all your prices, and set a true/false flag on each of them to indicate if they are selected. and then each time you execute updatePrice, you will need to loop through your array and add up the prices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM