[英]How to use the angular decimal pipe in typscript
I'm using the angular decimal pipe like this:我正在使用angular 十进制 pipe ,如下所示:
// Typescript
@Component({...})
export class ConfusionMatrixComponent {
@Input()
roundRules = '1.0-2';
}
// HTML:
<div class="value">{{ getIntensityNumber(i) | number: roundRules }}</div>
How can I use the same pipe but on a typescript function?如何在 typescript function 上使用相同的 pipe?
You can use Ng dependency injection.您可以使用 Ng 依赖注入。
Make sure to import the module and add DecimalPipe
to the providers array.确保导入模块并将
DecimalPipe
添加到提供程序数组。
providers: [DecimalPipe,...]
And then in your component.然后在你的组件中。
import { DecimalPipe } from '@angular/common';
class MyService {
constructor(private _decimalPipe: DecimalPipe) {}
transformDecimal(num) {
return this._decimalPipe.transform(num, '1.2-2');
}
}
An alternative approach to decimalPipe
is formatNumber decimalPipe
的另一种方法是formatNumber
I found in a similar question how to use it: just need to import DecimalPipe
from @angular/commun
and use it as a service:我在一个类似的问题中找到了如何使用它:只需要从
@angular/commun
导入DecimalPipe
并将其用作服务:
// Typescript
import { DecimalPipe } from '@angular/common';
@Component({...})
export class ConfusionMatrixComponent {
@Input()
roundRules = '1.0-2';
constructor(private decimalPipe: DecimalPipe) { }
getRoundNumber(num: number): string | null {
return this.decimalPipe.transform(num, this.roundRules) ?? '0';
}
}
// HTML:
<div class="value">{{ getRoundNumber(23.50873) }}</div>
Also, make sure you add the DecimalPipe to your providers
angular module:此外,请确保将 DecimalPipe 添加到您的
providers
angular 模块:
import { CommonModule, DecimalPipe } from '@angular/common';
@NgModule({
declarations: [...],
imports: [CommonModule],
exports: [...],
providers: [DecimalPipe]
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.