You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular如何实现输入框整数失焦后自动显示为3位小数?

Angular实现输入框失焦格式化为3位小数的原生方案

有完全基于Angular原生能力的实现方式,无需引入第三方依赖,以下是两种常用实现方案:

方案1:模板驱动表单 + 原生管道 + 失焦事件(适合单一场景)

该方案使用Angular自带的DecimalPipe和事件绑定能力实现,步骤如下:

  • 首先确保所在模块已导入@angular/common的CommonModule,DecimalPipe属于该模块的内置能力
  • 组件TS代码示例:
import { Component } from '@angular/core';
import { DecimalPipe } from '@angular/common';

@Component({
  selector: 'app-number-input',
  templateUrl: './number-input.component.html',
  providers: [DecimalPipe]
})
export class NumberInputComponent {
  inputValue: string = '';

  constructor(private decimalPipe: DecimalPipe) {}

  formatOnBlur(): void {
    const num = Number(this.inputValue);
    if (!isNaN(num)) {
      // 1.3-3 表示整数位至少1位,小数位固定3位
      this.inputValue = this.decimalPipe.transform(num, '1.3-3') || '';
    }
  }
}
  • 模板代码示例:
<!-- 用text类型避免浏览器原生number输入框自动抹除末尾小数零 -->
<input 
  type="text" 
  [(ngModel)]="inputValue" 
  (blur)="formatOnBlur()"
  placeholder="请输入数字"
>

注意:如果需要限制用户只能输入数字,可以额外加pattern="\d*\.?\d*"属性做原生校验。

方案2:自定义属性指令(适合多输入框复用场景)

利用Angular原生的指令能力封装通用逻辑,所有输入框加一行属性即可启用格式化:

  • 指令代码示例:
import { Directive, HostListener, ElementRef } from '@angular/core';
import { DecimalPipe } from '@angular/common';

@Directive({
  selector: '[threeDecimalFormat]',
  standalone: true, // 非standalone模式去掉该行,在模块declarations中声明即可
  providers: [DecimalPipe]
})
export class ThreeDecimalFormatDirective {
  constructor(private el: ElementRef<HTMLInputElement>, private decimalPipe: DecimalPipe) {}

  @HostListener('blur') onBlur() {
    const value = this.el.nativeElement.value;
    const num = Number(value);
    if (!isNaN(num)) {
      this.el.nativeElement.value = this.decimalPipe.transform(num, '1.3-3') || '';
    }
  }
}
  • 模板使用示例:
<input type="text" threeDecimalFormat placeholder="请输入数字">

两种方案都完全基于Angular官方提供的API实现,无需额外依赖,兼容Angular 12+所有版本。

内容的提问来源于stack exchange,提问作者Kirti Jha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 23:27:01