【问题标题】:Make input text accept numeric percent only Angular使输入文本仅接受数字百分比
【发布时间】:2021-11-23 18:18:38
【问题描述】:

如何让文本输入只接受百分比值?有没有办法通过删除非数值并在末尾添加“%”来做到这一点。

【问题讨论】:

    标签: html angular regex typescript


    【解决方案1】:

    为了使文本输入接受浮点数并在末尾添加“%”:

    • 在 html 文件中:
    <input id="id" type="text" formControlName="percentControl" (focusin)="start($event)"(focusout)="end($event)" />
    
    • 在 .ts 文件中:
      end(e) { 
        // console.log(/^[0-9.]*$/.test(e.target.value));
        if(!/^[0-9.]*$/.test(e.target.value))
            e.target.value = e.target.value.replaceAll(/[^0-9.]/g, '').trim();
       //add ' %' at the end
        if(e.target.value.length)
            e.target.value = e.target.value+ ' %';
        //this part is needed when working with angular form validation (ngForm required 
        //or formGroup Validators.required), else null value won't trigger the validation
        else 
            e.target.value = '0 %';
      }
      start(e) {
        e.target.value = e.target.value.replace('%', '').trim();
      }
    
    • 处理与后端之间的数据传输:
    1. 发布数据:
     //make sure to get rid from ' %' when posting data to the backend
     //example with formControl
     // the + is for converting string to number
     dataToPost = +this.form.get('percentControl').value.replaceAll('%', '');
    
    
    1. 获取数据:
     //Use Angular percent pipe
     local: string = "en-US";
     percentPipe:PercentPipe = new PercentPipe(this.local);
     myVariable = this.percentPipe.transform(dataFromBackEnd/100);
    
    

    【讨论】:

      猜你喜欢
      • 2010-12-17
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多