Angular 6 Reactive Form Input Value to Uppercase

I am using Reactive form in Angular 6. For input type text I want it to be uppercase. I tried the solution

(input)="form.patchValue({name: $event.target.value.toUpperCase()})"

The solution works fine, but the only problem when I move cursor to middle and type a character, the cursor moves at the end.

Is there any other approach or any better solution?

3 Answers

You can try this:

const yourControl = this.form.get('yourControlName');
yourControl.valueChanges.subscribe(() => {
  yourControl.patchValue(yourControl.value.toUpperCase(), {emitEvent: false});
});
0

why don't you just use CSS to do the job?

.uppercase{
  text-transform: uppercase;
}
<input class="uppercase" type="text" placeholder="type here">
3

I know this is reeeeally late, but...

You could hook on to the (change) event instead of the (input) event. Your case changes won't execute until after the user leaves the field, but it will prevent the cursor from jumping.

You case changes will still execute if the user submits the form by pressing Enter while in the field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest