简体   繁体   English

输入类型 = 数字验证在 angular 中无法正常工作

[英]Input type=number validation is not working correctly in angular

I want input type=number to accept decimal numbers between 0.1 and 0.9 (only one decimal number after dot, for example: 0.11 is not allowed), and also number 1.我希望 input type=number 接受 0.1 到 0.9 之间的十进制数(点后只有一个十进制数,例如:0.11 是不允许的),还有数字 1。
I'm trying to restrict that from a directive.我试图从指令中限制它。 It seems the directive works but then I press the submit button a value of the form control is incorrect.该指令似乎有效,但随后我按下提交按钮,表单控件的值不正确。
For example, if I type 0.11, 0.1 is shown in the input but form control has value of 0.11.例如,如果我输入 0.11,则输入中会显示 0.1,但表单控件的值为 0.11。
If I type a number from 1 to 9, input is empty but form control has value of that number.如果我输入一个从 1 到 9 的数字,则输入为空,但表单控件具有该数字的值。
Here is a stackblitz link: https://stackblitz.com/edit/angular-ivy-xa5g8v?file=src%2Fapp%2Fapp.component.ts这是一个stackblitz链接: https ://stackblitz.com/edit/angular-ivy-xa5g8v ? file = src%2Fapp%2Fapp.component.ts

This is happening because you are updating DOM but not the form model.发生这种情况是因为您正在更新 DOM 而不是表单模型。 One of the easiest and common way would be to emit event from directive and update the form model in event handler as shown below,最简单和常见的方法之一是从指令发出事件并在事件处理程序中更新表单模型,如下所示,

**Modified directive **修改后的指令

import { Component, Output, EventEmitter } from "@angular/core";
//other import statements

@Directive({
  selector: "[appLimitDecimal]"
})
export class LimitDecimalDirective {
  @Output()
  purgedValue: EventEmitter<any> = new EventEmitter();
  @HostListener("input", ["$event"])
  changes(evt: any) {
    const removeLastChar = evt.target.value.substring(
      0,
      evt.target.value.length - 1
    );
    // if decimal number length is bigger than 3
    if (evt.target.value.length > 3) {
      console.log("fromDirective", removeLastChar);
    }
    // decimal numbers from 0.1 to 0.9 and 1
    // remove last character if does not match regex
    if (!/^(?:0(?:\.[1-9])?|1)$/.test(evt.target.value)) {
      // evt.target.value = removeLastChar;
      this.purgedValue.emit(removeLastChar);
    }
  }
}

**Modified input element **修改输入元素

<input
  type="number"
  formControlName="numberInp"
   appLimitDecimal
  (purgedValue)="setValue($event)"
  min="0.1"
  max="1.0"
  step="0.1"
 />

Finally, add following callback method in app.component.ts最后,在 app.component.ts 中添加如下回调方法

  setValue(val) {
    this.f.patchValue({ numberInp: val });
  }

I hope this is helpful to you.我希望这对你有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM