36

Is there a way to use math functions in angular2 bindings?

example

<div class="partition-panel">
                <b class="pull-left">{{Math.round(variable/12*2)}}</b>
                <b class="pull-right">{{Math.round(variable/12*2)}}</b>
 </div>

when try to use this i got error

Cannot read property 'round' of undefined

Also the similar question is answered for angular1

1
  • 1
    The problem is, from the template you only have access to the local scope of your Component, so you either have to define a helper method or assign window.Math to a member variable like Adrien suggested. Commented Nov 16, 2016 at 13:16

2 Answers 2

89

You can try this :

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{Math.round(number)}}</h2>
    </div>
  `,
})
export class App {
  Math = Math;
  number = 2.5;
}

DEMO

Sign up to request clarification or add additional context in comments.

2 Comments

This worked, but I had to move the declaration to the component whose template needed Math.
You should be also able to avoid init Math on the constructor and simply write: Math: Math = Math;
13

For rounding numbers in Angular templates, you can use the DecimalPipe: {{ value | number }}

See all the rounding options in https://angular.io/api/common/DecimalPipe

For all the built-in pipes, check https://angular.io/api?type=pipe

3 Comments

This should be the accepted answer as it makes use of pipes instead of using functions in template bindings. Also less code needed than declaring Math as a variable.
Careful though, as the rounding done by the pipe is different for negative numbers.
There are no real rounding options though. This only rounds "to-nearest" per the docs and does not replace floor() or ceil().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.