1

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.

8
  • 1
    There are multiple ways to do this: validators, custom directive or event handling for example Commented Dec 14, 2017 at 17:25
  • 1
    My use case is not validation, I want to have input state stored outside of the component Commented Dec 14, 2017 at 17:33
  • 1
    @JBNizet my use case is not validation. I want to keep and control input state from outside of the component Commented Dec 14, 2017 at 18:20
  • 1
    @JBNizet maybe the example is a little bit misleading. I want to achieve the same behaviour as with React's controlled components Commented Dec 14, 2017 at 18:25
  • 2
    @JBNizet you are not 5 years old, you can read, please follow the link in the question. I've also removed example since it was a bit misleading Commented Dec 14, 2017 at 18:44

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This solution is almost it. As mentioned it is a low level, you have to handle backspace, shift, etc.
1

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]

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 changes
  • formControl.setValue function to update the inner state of the FormControl

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!!

Comments

0

You could use maxlength attribute of an input element

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.