简体   繁体   中英

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?

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

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

You can try this:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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