【问题标题】:update input number while typing键入时更新输入数字
【发布时间】:2020-01-09 15:37:04
【问题描述】:

我需要使用包含数字并具有最小值和最大值的 angular 2+ 进行输入 html。 我希望如果用户键入小于最小输入的数字,将使用 min 更新并收到此消息:自动最小数字为 2。 感谢您的帮助。

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    这是你要找的吗?

    如果是,您可以使用验证器轻松改进它。

    import { Component, OnInit } from '@angular/core';
    import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
    import { debounceTime } from 'rxjs/operators';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: [ './app.component.css' ]
    })
    export class AppComponent implements OnInit {
    
      min = 5;
      max = 15;
      form: FormGroup;
    
      constructor(private fb: FormBuilder) {
        this.form = this.fb.group({
          num: new FormControl('')
        });
      }
    
      ngOnInit() {
        this.form.get('num').valueChanges
        .pipe(debounceTime(500))
        .subscribe(value => {
          if (!value) {
            return;
          }
    
          if (value < this.min) {
            this.form.setValue({
              num: this.min
            }, {
              emitEvent: false
            });
          } else if (value > this.max) {
            this.form.setValue({
              num: this.max
            }, {
              emitEvent: false
            })
          }
        });
      }
    
    <form [formGroup]="form">
      <input type="number" formControlName="num" placeholder="Type a number"/>
    </form>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-02
      • 2018-09-21
      • 1970-01-01
      • 2014-10-21
      • 1970-01-01
      • 1970-01-01
      • 2021-11-03
      • 2012-04-03
      相关资源
      最近更新 更多