html code
<table>
<thead>
<tr>
<th>Items</th>
<th>Value</th>
<th>% of value</th>
<th>Rate</th>
<th>Calculated Value</th>
</tr>
</thead>
<tbody formArrayName="Details">
<tr *ngFor="let item of Details.controls;">
<td>
<input class="width-15" matInput type="text" formControlName="ItemName" autocomplete="off">
</td>
<td>
<input matInput type="text" mask="comma_separator.2" prefix="$" autocomplete="off" formControlName="Value">
</td>
<td>
{{percentOfValue(item, Details.controls)}}
</td>
<td>
<input matInput type="text" mask="comma_separator.2" suffix="%" autocomplete="off" formControlName="Rate">
</td>
<td>
<input matInput type="text" mask="comma_separator" prefix="$" autocomplete="off"
formControlName="CalculatedValue" value="{{calculatedvalue(item)}}">
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Totals</td>
<td>
${{ sumColumnTotal('Value') }}
</td>
<td>
{{ sumPercentColumnTotal('percentOfValue') }} ------------- How to calculate the sum of this column???
</td>
<td>
// No need of totals for rates.
</td>
<td>
${{ sumColumnTotal('Value') }}
</td>
</tr>
</tfoot>
</table>
**.ts code**
CalculatedValue(item): string {
return ((item.value.Value) * (item.value.Rate));
}
// (item value / Sum of all rows)*100 - Dynamic column. When value changes in 2nd column the 3rd column values will be updated automatically. percentOfValue(item, allItems): string {
const totalValue = allItems.map(c => c.value.Value)
.reduce((sum, current) => {
const value = current != null ? current : 0;
return +this.tryCleanNumber(sum) + +this.tryCleanNumber(value);
}, 0);
if (totalValue === 0) {
return '0%';
}
const percent = +this.tryCleanNumber(item.value.Value) / totalValue;
// * 100 for percent, *100 again and /100 for rounding
const rounded = (percent * 100 );
return rounded + '%';
}
Result table in the UI
Issues with red highligted fields:
- Calculated Value column total works as expected when we input values in the text box (last column). But Inputting some values in Value (2nd column), would auto populate/calculate the last column value (calculatedvalue). In other words, totals are not working on a "calculated column" but works well when the column in inputted.
- Advise how to calculate the totals of 3rd column (% of value). Couldn't write any function in ts as the column itself is a calculated column.