angular2绑定中的数学函数

Jag*_*raj 22 typescript math-functions angular

有没有办法在angular2绑定中使用数学函数?

<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>
Run Code Online (Sandbox Code Playgroud)

当试图使用这个我得到错误

Cannot read property 'round' of undefined
Run Code Online (Sandbox Code Playgroud)

对于angular1,也回答了类似的问题

Adr*_*RAL 56

你可以试试这个:

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

DEMO

  • 您还应该能够在构造函数上避免使用init Math,只需编写:Math:Math = Math; (3认同)

Ani*_*oud 10

对于 Angular 模板中的四舍五入数字,您可以使用 DecimalPipe: {{ value | number }}

查看https://angular.io/api/common/DecimalPipe 中的所有舍入选项

对于所有内置管道,请检查 https://angular.io/api?type=pipe