首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 ><输入matInput .(角度材质形式)允许输入3个小数点,但只显示2个小数点。

问<输入matInput .(角度材质形式)允许输入3个小数点,但只显示2个小数点。
EN

Stack Overflow用户
提问于 2020-06-17 22:06:46
回答 1查看 4.1K关注 0票数 0

我有一个规则的角度材料形式,它使用numberMaskOptions限制输入和显示场值的3个小数点。(见下文代码)

这很好,但是客户现在希望将字段的“显示”限制为只显示两个小数点,但希望允许用户在同一个字段中输入3个小数点。

换句话说,当光标不在字段中时,它应该显示两个小数点的精度,但是当用户进入该字段编辑它时,它应该允许3个小数点的精度。

这与材料matInput字段是可能的吗?如果是的话,怎么做?如果没有,我还应该如何处理呢?

代码语言:javascript
复制
    <div *ngIf="isFieldVisible">
      <mat-form-field myAppTooltip>
        <mat-label>Insect Body Size</mat-label>
        <input
          autocomplete="off"
          appNumberMask
          formControlName="InsectBodySizeSmm"
          matInput
          max="99999"
          min="0"
          [numberMaskOptions]="threeDecPrecisionDecimalMaskOptions"
        />
        <mat-error></mat-error>
      </mat-form-field>
    </div>

我的面具

代码语言:javascript
复制
threeDecPrecisionDecimalMaskOptions = {
      align: 'right',
      allowNegative: false,
      decimalSeparator: '.',
      precision: 3,
      prefix: '',
      suffix: '',
      thousandsSeparator: '',
      valueMode: 'standard',
    };

这允许我输入并查看字段表单中的值到小数点3。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-18 00:00:09

不久前,我做了一个类似的指令,您可以在此链接中看到,我不知道您是否可以使用,因为您也有一个指令来掩盖数字。

守则如下:

代码语言:javascript
复制
@Directive({ selector: "[decimal2]" })
export class Decimal2 implements OnInit {
  private el: HTMLInputElement;
  private value: any;
  constructor(private elementRef: ElementRef) {
    this.el = this.elementRef.nativeElement;
  }
  @HostListener("focus", ["$event.target.value"])
  onFocus() {
    this.el.value = this.value;
  }

  @HostListener("blur", ["$event.target.value"])
  onBlur(value: any) {
    this.transform(value);
  }
  ngOnInit() {
    this.transform(this.el.value);
  }
  transform(value: any) {
    this.value = value;
    if (value && !isNaN(value)) {
      const aux = "" + Math.round(+this.value * 100);
      this.el.value = aux.slice(0, -2) + "." + aux.slice(-2);
      if (this.el.value.indexOf(this.value) >= 0) this.value = this.el.value;
    }
  }
}

更新的我们可以使用变换函数中的角formatNumber来改进我们的指令

代码语言:javascript
复制
  transform(value: any) {
    this.value = value;
    if (value && !isNaN(value)) {
      this.el.value=formatNumber(+this.value, "en-US", '1.2-2');
      const formated=this.el.value.split(',').join('')
      if (formated.indexOf(this.value) >= 0) this.value = formated;
    }
  }
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62439134

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档