首页 > 解决方案 > 仅计算 Angular Material 选择列表的选定值

问题描述

我有一个简单的 Angular Material 选择列表,里面有一些值。

我的要求是仅计算所选(检查)值的总和(然后,如果价格超过某个金额,则对价格应用折扣)。

我相信这一定很容易,但我是 Angular 和 Material 组件的新手,不知何故无法在谷歌或这里找到我想要的东西......我的代码如下:

HTML

 <mat-selection-list #options>
    <mat-list-option *ngFor="let option of optionArray">
      {{option.name}} - ${{option.price}}

    </mat-list-option>
  </mat-selection-list>

  <p>
    You have selected {{options.selectedOptions.selected.length}} items with total sum of $ {{  }}. </p>
  <p *ngIf="">
    Your discount is 10%. </p>

TS

interface Options {
  name: string;
  price: number;
}

optionArray: Options[] = [
    {
      name: 'Item 1',
      price: 4000
    },
    {
      name: 'Item 2',
      price: 8000
    },
    {
      name: 'Item 3',
      price: 3500
    },
    {
      name: 'Item 4',
      price: 500
    }
  ]

先感谢您!

标签: angularangular-material

解决方案


将模型和更改事件附加到您的 mat-selection-list 元素,然后,您可以使用 javascript 方法:map、reduce。

HTML:

<mat-selection-list #options [(ngModel)]="selectedOptions" (ngModelChange)="onSelectedOptionsChange($event)">
    <mat-list-option *ngFor="let option of optionArray">
        {{option.name}} - ${{option.price}}
    </mat-list-option>
</mat-selection-list>

<p>
    You have selected {{selectedOptions.selected.length}} items with total sum of $ {{ totalSum }}. </p>
<p *ngIf="..."> Your discount is 10%. </p>

TS控制器:

onSelectedOptionsChange() {
    this.totalSum = this.selectedOptions
        .map((option: Options) => option.price)
        .reduce((priceA: number, priceB: number) => priceA + priceB)
}

希望这可以帮助。


推荐阅读