石井友*_*井友梨 4 angular-material angular
我有一个简单的 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>
Run Code Online (Sandbox Code Playgroud)
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
}
]
Run Code Online (Sandbox Code Playgroud)
先感谢您!
将模型和更改事件附加到您的 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>
Run Code Online (Sandbox Code Playgroud)
TS控制器:
onSelectedOptionsChange() {
this.totalSum = this.selectedOptions
.map((option: Options) => option.price)
.reduce((priceA: number, priceB: number) => priceA + priceB)
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
346 次 |
| 最近记录: |