madox2
madox2

Reputation: 51911

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.

Upvotes: 1

Views: 2352

Answers (3)

Eric Van Der Dijs
Eric Van Der Dijs

Reputation: 136

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

Upvotes: 1

sodik
sodik

Reputation: 4683

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.

Upvotes: 1

Ramiro Uvalle
Ramiro Uvalle

Reputation: 241

You could use maxlength attribute of an input element

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

Upvotes: 0

Related Questions