'Controlled input component in Angular 4
Is there any way how to control value of input only by on change handler in angular 4?
I would like to achieve the same behaviour as with React's controlled components.
My final use case is to keep input state outside of the component in the store which emits state changes.
Solution 1:[1]
One way is to not used ngForms at all and use input field directly:
<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.
Solution 2:[2]
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()
}
that way you can control what your input stores in memory, in this case saving the string as uppercase.
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
formControl.valueChanges
observable to observe the changesformControl.setValue
function to update the inner state of theFormControl
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!
PS: I'm not too proficient in angular, so if there is a better way of doing things, I'm open to suggestions!!
Solution 3:[3]
You could use maxlength attribute of an input element
<input type="text" [ngModel]="value" maxlength="3">
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | sodik |
Solution 2 | |
Solution 3 | Ramiro Uvalle |