angular - 仅计算 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
}
]
先感谢您!
解决方案
将模型和更改事件附加到您的 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)
}
希望这可以帮助。
推荐阅读
- ocaml - 在 Ocaml 的递归函数中调用递归函数时出现语法错误
- powershell - 从文件夹名称更改文件日期的脚本
- linux - 无法安装新内核,在安装 EVDI 的 DKMS 上挂起
- c++ - Assimp opengl加载模型顶点一些大于1的值
- assembly - 汇编语言是如何编译的?
- typescript - 如何键入基于提供的参数返回对象属性的函数?
- python - 从python中的面向对象函数访问变量
- vb.net - 使用块范围问题
- mongodb - $lookup 聚合未能显示数组值
- python - 错误 pandas np.where ValueError:使用可迭代设置时必须具有相等的 len 键和值