Dev Tin
Dev Tin

Reputation: 157

how to sum up total in angular?

I want to sum the column of a table in angular but it does not work: for example if I want to sum the 2000 and 3000 and 4000 it gives me 200030004000, but I want to sum it means 9000, it is concatenation.

client.component.ts

clients: Client[];
total: number=0;

constructor(private clientService:ClientService) { }

ngOnInit() {
    this.clientService.getClients().subscribe(clients => {
        this.clients=clients;
        this.total = this.getTotal();
    });
}

getTotal() {
    return this.clients.reduce((total, client) => {
        return total + client.balance;
    }, 0)
}

client.component.html

<div class="col-md-6">
    <h4 class="text-right">Total : {{ total | currency:"USD": "symbol" }}</h4>
</div>

Upvotes: 1

Views: 443

Answers (2)

Mustafa Kunwa
Mustafa Kunwa

Reputation: 867

You can try this: Because the balance you are getting is in string maybe

getTotal() {
    return this.clients.reduce((total, client) => {
      return total + parseInt(cliient.balance);
    }, 0)
}

Upvotes: 0

Adrita Sharma
Adrita Sharma

Reputation: 22203

Try:

...
return total + Number(client.balance);
...

Upvotes: 5

Related Questions