问题描述
我有一个带下拉列表的角度物料表,用户可以通过该表选择时间长度。在用户提供了时间之后,我想计算每种服务类型的服务费用,然后进行总计以总计所有选定服务的总计。 [1]:https://i.stack.imgur.com/m2ukB.jpg
问题是所有行的总计(价格*月)基于上次选择的月数而动态变化,尽管先前选择的月保持不变。 这是我的模板
......
<ng-container matColumnDef="price">
<mat-header-cell *matHeaderCellDef mat-sort-header> Price (USD/m) </mat-header-cell>
<mat-cell *matCellDef="let element"> {{element.price | currency}} </mat-cell>
</ng-container>
<ng-container matColumnDef="month">
<mat-header-cell *matHeaderCellDef> Months </mat-header-cell>
<mat-cell *matCellDef="let element">
<mat-select placeholder="0" (selectionChange)="onChangeMonth($event)">
<mat-option *ngFor="let month of months" [value]="month.value">
{{ month.viewValue }}
</mat-option>
</mat-select>
</mat-cell>
</ng-container>
<ng-container matColumnDef="subtotal">
<mat-header-cell *matHeaderCellDef> SubTotal </mat-header-cell>
<mat-cell *matCellDef="let element">
{{element.price * serviceLength}}
</mat-cell>
</ng-container>
......
这是我的ts:
export class StockAddsubsComponent implements OnInit {
columnsTodisplay: string[] = ['id','name','price','month','subtotal'];
listData: MatTableDataSource<any>;
months: any [] = [{value: 1,viewValue: 1},{value: 3,viewValue: 3},{value: 6,viewValue: 6},{value: 12,viewValue: 12}
];
serviceLength: number;
@ViewChild(MatSort) sort: MatSort;
constructor(private feesService: FeesService) { }
ngOnInit(): void {
this.createFeeList();
}
createFeeList() {
this.feesService.getFeeList().subscribe((data: []) => {
this.listData = new MatTableDataSource(data);
},error => {
console.log(error);
});
}
onChangeMonth(event) {
this.serviceLength = event.value;
}
}
解决方法
只需在您的[(ngModel)]="element.month"
中使用mat-select
<mat-select placeholder="0" [(ngModel)]="element.month">
<mat-option *ngFor="let month of months" [value]="month.value">
{{ month.viewValue }}
</mat-option>
</mat-select>
并使用{{element.price*element.month}}
注意:您也可以使用吸气剂获取总量并将其放在表格的页脚中
get total()
{
return this.listData.data.map(x=>x.month*x.price).reduce((a,b)=>a+b)
}
请参见stackblitz