How can i calculate the sum of table column in angular 2+?
Create a new filter pipe that calculates the sum with the current filter
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filtercount'
})
export class FilterPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if(!items) return [];
if(!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter( it => {
return it.name.toLowerCase().includes(searchText);
}).reduce((a, b) => a.total + b.total, 0);
}
}
and use it like this
{{records | filtercount:profile}}
angular 2 how to totals column ngFor?
Create a function in you component to get the sum and call it on ui something like
in you component
getTotal(arr){
return arr.reduce( (sum, curr) => sum + curr.Total,0 );
}
Then on ui
<tr *ngFor="let monitoring of monitorings">
....
</tr>
<tr><td>{{getTotal(monitorings)}}</td></tr>
This example is only for Total
property same can be done for Done,Not Done
etc
Calculate sum of data in an Angular Material Table column that can be fetched from back-end
First you need to make avalailable lines on TableDataSource;
getLines(){
return this.linesSubject
}
then in your calculateTotal method
calculateTotal(){
this.dataSource.getLines().subscribe(lines => {
this.totalAmount = lines.reduce((total,line) => total + line.amount ,0)
})
}
How to calculate sum of table columns and show in footer using Angular?
There are instructions in the angular material documentation and also a sample in the examples.
What you need to do is define a footer cell in a similar fashion you do for the headers in every column. In the column bindings for the footer column you define directly how you calculate the sum. There is no need to add another row with the total data. After that you just add also a footer row definition and it all works.
Here is the changed template from your sample:
<mat-table [dataSource]="dataSource">
<!-- Columns -->
<ng-container matColumnDef="player">
<mat-header-cell *matHeaderCellDef> Player </mat-header-cell>
<mat-cell *matCellDef="let player"> {{ player.name }}</mat-cell>
<mat-footer-cell *matFooterCellDef></mat-footer-cell>
</ng-container>
<ng-container matColumnDef="team">
<mat-header-cell *matHeaderCellDef> Team </mat-header-cell>
<mat-cell *matCellDef="let player"> {{ player.team }}</mat-cell>
<mat-footer-cell *matFooterCellDef></mat-footer-cell>
</ng-container>
<ng-container matColumnDef="goals">
<mat-header-cell class="right-align" *matHeaderCellDef> Goals </mat-header-cell>
<mat-cell class="right-align" *matCellDef="let player"> {{ player.goals }}</mat-cell>
<mat-footer-cell *matFooterCellDef> Total: {{ calculateTotal() }}</mat-footer-cell>
</ng-container>
<!-- Rows -->
<mat-header-row class="sticky-header" *matHeaderRowDef="['player', 'team', 'goals']"></mat-header-row>
<mat-row *matRowDef="let row; columns: ['player', 'team', 'goals']"></mat-row>
<mat-footer-row class="sticky-footer" *matFooterRowDef="['player', 'team', 'goals']"></mat-footer-row>
</mat-table>
And also the changed component code so you see you do not need to modify the data.
export class AppComponent {
dataSource: PlayerDataSource;
isLastRow = (data, index) => index === this.players.length;
players = STATS.slice();
constructor() {
this.dataSource = new PlayerDataSource();
this.dataSource.use(this.players.slice());
}
public calculateTotal() {
return this.players.reduce((accum, curr) => accum + curr.goals, 0);
}
}
export class PlayerDataSource extends DataSource<PlayerOrTotal> {
dataWithTotal = new BehaviorSubject<PlayerOrTotal[]>([]);
use(players: Player[]) {
this.dataWithTotal.next([ ...players]);
}
connect(): Observable<PlayerOrTotal[]> {
return this.dataWithTotal.asObservable();
}
disconnect() {}
}
I have created also a fork of your StackBlitz where you can see it working.
angular 2 how to sum column ngFor
You would have to create a getSum(index: number): number method in your Angular 2 Component class, something like this:
getSum(index: number) : number {
let sum = 0;
for(let i = 0; i < this.items.length; i++) {
sum += this.items[i][index];
}
return sum;
}
and in your html, replace your SUMX by:
<td>{{ getSum(0) }} </td><td>{{ getSum(1) }}</td> ...
And you could of course also use a ngFor to create the multiple td tags if needed.
[EDIT]: to have the exact code you need based on your fiddle:
getSum(column) : number {
let sum = 0;
for(let i = 0; i < this.list.length; i++) {
sum += this.list[i][column];
}
return sum;
}
and in html:
<td>{{ getSum('newInput') }}</td><td>{{ getSum('newOutput') }}</td>
[EDIT 2]: just for completeness, you can also do the sum of an array using the reduce function rather than using a loop in the getSum method:
var sum = this.items[i]['myfield'].reduce(function(x, y) { return x + y; }, 0);
Calculate the sum of each column of an HTML table in Typescript
Is there any way to do that in typescript?
Yes but not in the *ngFor
directly. Create your final object graph in the ngOnInit
function and then display the values using the template and *ngFor
.
Here is an example but keep in mind you did not illustrate what you expect the totals to be or where they come from. You did not actually do anything with the year value or index.
As a side note you can use an html column span instead of creating empty or repetitive columns. This is in reference to the first row.
export class Sum implements OnInit {
basePay: number;
bonusPercent: number;
data: {incentives: number[], ttc: number[], totals?: number[]};
ngOnInit() {
this.basePay = 10000;
this.bonusPercent = 0.12;
const years = [0,1,2,3,4];
data = {
incentives: years.map(_=> basePay * bonusPercent),
ttc: years.map(_ => basePay + (basePay * bonusPercent)),
};
data.totals = years.map((_,i) => data.incentives[i] + data.ttc[i]);
}
}
<table>
<tr>
<td>Base</td>
<td colspan="5"> {{basePay}} </td>
</tr>
<tr>
<td>Variable incentive</td>
<td *ngFor="let incentive of data.incentives">{{ incentive }}
</td>
</tr>
<tr>
<td>Total Target Cash (TTC) (Local) </td>
<td *ngFor="let ttc of data.ttc">{{ ttc }}
</tr>
<tr>
<td>Sum</td>
<td *ngFor="let total of data.totals">{{ total }}
</tr>
</table>
Get SUM of a table column with 'for loop' in angular2
If you want to loop the array stored in this.Par
, you can use forEach
directly:
var total = 0;
this.Par.forEach((item, index) => {
total += this.getShots(item) || 0
});
Get the Total Sum of Column in Angular
In 3rd column in the html you have:
<td> <span ng-model="x.amount" ng-change="sumByColumn()">{{ x.number*x.amount }}</span> </td>
A multiplication:
x.number * x.amount
But here you miss that :
.filter('sumByColumn', function () {
return function (collection, column) {
var total = 0;
collection.forEach(function (item) {
total += parseInt(item[column]);
});
return total;
};
})
I guess if you add that multiplication you going to get the correct total:
parseInt(item[column]*item.number);
angular add a sum column
let total = 0;
let value = 0;
ngOnInit(): void {
this.findSum();
}
findSum(data) {
for(d in data) {
total += data.value;
}
return total;
}
<table mat-table [dataSource]="data">
<ng-container matColumnDef="sum">
<th mat-header-cell *matHeaderCellDef> Total: </th>
<td mat-cell *matCellDef="let d"> {{d.total}} </td>
</ng-container>
</table>
How to sum up the values entered in the mat-table column using mat-input in angular2
try this
In component
ngOnInit(){
this.accdetailservice.accountdetails()
.subscribe(data =>
this.dataSource1.data= data.map(obj => ({...obj, value: 0}))
);
}
calculation(){
return dataSource1.data.reduce((summ, v) => summ += parseInt(v.value), 0)
}
in Html
<mat-grid-tile> Total: {{calculation()}}</mat-grid-tile>
also change <input matInput value=0>
to <input matInput value="element.value"/>
as per the chat discussion you need to use value parameter as a dynamic parameter to calculate
So try this below way
<ng-container matColumnDef="value">
<mat-header-cell *matHeaderCellDef> Value </mat-header-cell>
<mat-cell *matCellDef="let element">
<ng-container>
<input [(ngModel)]="element.value">
</ng-container>
</mat-cell>
</ng-container>
Related Topics
Show Only a Limited Number of Rows in a Table
Angular:How to Implement Condtion Based Click Event
Prevent Form Submission on Enter Key Press
Javascript Sum and Group by of Json Data
Mongodb Get Data to Display in HTML
How to Trigger a Click Event on Disabled Elements
Change Specific Button Text on Click Inside Ngfor
Slick Carousel - Force Slides to Have the Same Height
How to Get Line Break Within String Interpolation in Angularjs
Formdata Created from an Existing Form Seems Empty When I Log It
Calculate Percentage JavaScript
React Component Not Re-Rendering When State Changes
How to Get the Index from a Json Object With Value
Calculate and Display % Discount for Price Classes JavaScript
How to Remove a Json Inside a Json by a Key Using Jquery
Best Way to Show a Loading Spinner/Gif While My React Component Is Fetching Via Ajax