Math functions in AngularJS bindings

后端 未结 13 1162
无人及你
无人及你 2020-11-29 17:55

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

e.g.

The percentage is {{Math.round(100*count/total)}}%

13条回答
  •  时光取名叫无心
    2020-11-29 18:21

    Angular Typescript example using a pipe.

    math.pipe.ts

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'math',
    })
    
    export class MathPipe implements PipeTransform {
    
      transform(value: number, args: any = null):any {
          if(value) {
            return Math[args](value);
          }
          return 0;
      }
    }
    

    Add to @NgModule declarations

    @NgModule({
      declarations: [
        MathPipe,
    

    then use in your template like so:

    {{(100*count/total) | math:'round'}}
    

提交回复
热议问题