简体   繁体   English

Angular - 使用 ngModel 和 ngModelChange 手动限制输入的最大值

[英]Angular - Manually restricting max value of input using ngModel and ngModelChange

I'm trying to manually restrict user from enter a value in input more than a certain value.我正在尝试手动限制用户在输入中输入的值超过某个值。 I'm using Angular 9 and ngModel on the input.我在输入上使用 Angular 9 和 ngModel。

As you can see in the below code, on ngModelChange, if the input value for age is larger than 27, I'm setting it to 27.正如您在下面的代码中看到的那样,在 ngModelChange 上,如果age的输入值大于 27,我将其设置为 27。

If the user inputs a bigger number like 144, it displays 27 in the input box as soon as the user types the last 4. But for numbers that have 27 as the prefix, eg 271, 2700, etc., the value displayed in input box is not changed.如果用户输入更大的数字,如 144,则在用户输入最后一个 4 时,它会在输入框中显示 27。但对于以 27 为前缀的数字,例如 271、2700 等,输入中显示的值盒子没变。 Does anyone know why and is there a way to have it display correctly?有谁知道为什么,有没有办法让它正确显示?

Please note that the variable age is set correctly to 27 for all larger numbers.请注意,对于所有较大的数字,变量age正确设置为 27。 Just that the input box display does not change for numbers that have 27 as the prefix.只是对于以 27 为前缀的数字,输入框显示不会改变。

Here is the Codepen link: https://codepen.io/baggasumit/pen/MWVgaqZ这是 Codepen 链接: https ://codepen.io/baggasumit/pen/MWVgaqZ

@Component({
  selector: 'my-app',
  template: `
   <h1>ngModel Example</h1>
   <label>Age </label>
   <input type="number" max="27" [ngModel]="age" (ngModelChange)=onAgeChange($event) />
   <br>
   <br>
   <div>Age is set to {{age}}</div>
  `
})
class AppComponent {
  public age;
  
  public onAgeChange(newAge) {
    if (newAge > 27) {
      this.age = 27;
    } else {
      this.age = newAge;
    }
    console.log(this.age);
  }
}

You need to also update the html element input's #myInput value.您还需要更新 html 元素输入的#myInput值。

const { Component, VERSION } = ng.core;

@Component({
  selector: 'my-app',
  template: `
   <h1>ngModel Example</h1>
   <label>Age </label>
   <input type="number" #myInput [(ngModel)]="age" (ngModelChange)=onAgeChange(myInput) />
   <br>
   <br>
   <div>Age is set to {{age}}</div>
  `
})
class AppComponent {
  public age;
  
  public onAgeChange(myInput) {
    if (this.age > 27) {
      this.age = 27;
    } 
    myInput.value = this.age
    console.log(this.age);
  }
}


// main.js
const { BrowserModule } = ng.platformBrowser;
const { NgModule } = ng.core;
const { CommonModule } = ng.common;
const { FormsModule } = ng.forms;

@NgModule({
  imports: [
    BrowserModule,
    CommonModule,
    FormsModule,
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent],
  providers: []
})
class AppModule {}

const { platformBrowserDynamic } = ng.platformBrowserDynamic; 

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .catch(err => console.error(err));

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

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