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

Angular实现带后缀单位的文本框:输入时单位右移且仅取数值

Angular 带动态单位的输入框实现

效果说明

  • 初始状态:单位显示在输入框内部,与输入框融为一体
  • 输入状态:输入内容后,单位自动移到输入框右侧,保持对齐

1. 模板(HTML)实现

在组件模板中创建包含输入框和单位的容器,通过ngModel绑定值,用ngClass根据输入内容切换单位样式:

<div class="input-unit-container">
  <input 
    type="number" 
    [(ngModel)]="inputValue" 
    class="unit-input" 
    placeholder="请输入数值"
  >
  <span class="unit-label" [ngClass]="{'unit-shifted': inputValue}">kg</span>
</div>

2. 样式(CSS/SCSS)实现

通过CSS控制容器、输入框和单位的布局,利用ngClass切换类实现单位位移:

.input-unit-container {
  position: relative;
  display: inline-block;
}

.unit-input {
  padding-right: 30px; /* 预留单位位置 */
  height: 36px;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding-left: 8px;
  font-size: 14px;
}

.unit-label {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  font-size: 14px;
  transition: all 0.2s ease;
}

.unit-shifted {
  right: -25px; /* 输入时单位右移 */
  color: #333;
}

3. 组件逻辑(TS)实现

在组件类中定义绑定变量,添加提取纯数值的方法:

import { Component } from '@angular/core';

@Component({
  selector: 'app-unit-input',
  templateUrl: './unit-input.component.html',
  styleUrls: ['./unit-input.component.scss']
})
export class UnitInputComponent {
  inputValue: string | number = '';

  // 获取纯数值部分
  getNumericValue(): number | null {
    if (!this.inputValue) return null;
    // 匹配开头的数字(支持小数)
    const numericMatch = String(this.inputValue).match(/^\d+(\.\d+)?/);
    return numericMatch ? parseFloat(numericMatch[0]) : null;
  }

  // 示例:提交时获取数值
  onSubmit() {
    const numericValue = this.getNumericValue();
    console.log('提取的数值:', numericValue);
    // 后续业务逻辑处理
  }
}

关键说明

  • 单位位移:通过ngClass判断inputValue是否有值,切换unit-shifted类实现位置平滑过渡
  • 数值提取:使用正则匹配输入内容开头的有效数字(包含小数),确保只获取数值部分

内容的提问来源于stack exchange,提问作者Mahesh Dharwad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 13:48:12