简体   繁体   English

Angular 4中的受控输入组件

[英]Controlled input component in Angular 4

Is there any way how to control value of input only by on change handler in angular 4?有什么方法可以仅通过 angular 4 中的更改处理程序来控制输入值?

I would like to achieve the same behaviour as with React's controlled components .我想实现与 React 的受控组件相同的行为。

My final use case is to keep input state outside of the component in the store which emits state changes.我的最终用例是将输入 state 保留在商店中发出 state 更改的组件之外。

One way is to not used ngForms at all and use input field directly: 一种方法是根本不使用ngForms并直接使用输入字段:

<input type="text" [value]="value" (keydown)="onChange($event)" />

and then in your component 然后在你的组件中

  onChange(e) {
    e.preventDefault();
    this.value = e.key;
  }

in this way you have full control - but it is rather low level - you must build your value always manually key by key. 通过这种方式,您可以完全控制-但级别较低-您必须始终手动逐个键地建立自己的价值。

I believe that what you can do is the following:我相信你可以做的是:

First, in yout template首先,在你的模板中

<input
  type="text"
  [ngModel]="value"
  (ngModelChange)="onValueChange($event)"
/>

Second, in your component其次,在你的组件中

onValueChange(newValue: string) {
  this.value = newValue.toUpperCase()
}

[reference: v13 , v9 , v4 ] [参考: v13v9v4 ]

that way you can control what your input stores in memory, in this case saving the string as uppercase.这样你就可以控制你的输入存储在 memory 中的内容,在这种情况下将字符串保存为大写。

Also keep in mind that this might not be the most propper way of doing things in angular, I believe the optimal way is to use FormControl and FormGroup , if your are using those, you can obtain a reference of the FormControl in your component and use the还要记住,这可能不是 angular 中最合适的做事方式,我相信最佳方式是使用FormControlFormGroup ,如果您正在使用它们,您可以在组件中获取 FormControl 的引用并使用这

  • formControl.valueChanges observable to observe the changes formControl.valueChanges observable 观察变化
  • formControl.setValue function to update the inner state of the FormControl formControl.setValue function 更新FormControl的内部state

I know this answer probably comes a bit late, but for all of those like me who are coming to angular from react, hope this helps you!我知道这个答案可能有点晚了,但对于所有像我一样从 React 来到 angular 的人,希望这对你有帮助!

PS: I'm not too proficient in angular, so if there is a better way of doing things, I'm open to suggestions!! PS:本人对angular不是很精通,如果有更好的做法欢迎大家指教!!

您可以使用输入元素的maxlength属性

<input type="text" [ngModel]="value" maxlength="3">

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

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