1

What is the right way to ensure that any input that is typed into a text box in angular8 is in uppercase?

I tried applying a style to the input tag

text-transform:uppercase

, but it looks like while the appearance of text typed into the input box is in uppercase, the value that is actually stored in the

[(ngModel)]

does not show up as uppercase in uppercase.

ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
Rolando
  • 58,640
  • 98
  • 266
  • 407

4 Answers4

4

You can split [(ngModel)] into [ngModel] and (ngModelChange), and convert the input text to uppercase in the event handler:

<input [ngModel]="value" (ngModelChange)="value = $event.toUpperCase()" />

However, there is a problem when a lowercase letter is inserted at the beginning or in the middle of the input text: the caret automatically moves to the end of the text. The technique suggested in this article can be used to maintain the caret position, as shown in the following improved code:

<input #txt [ngModel]="value" (ngModelChange)="value = convertToUpperCase(txt, $event)" />
public convertToUpperCase(input: HTMLInputElement, val: string) {
  // Save caret position
  const start = input.selectionStart;
  const end = input.selectionEnd;
  setTimeout(() => {
    // Restore caret position after returning the converted string
    input.setSelectionRange(start, end);
  });
  // Return the input string converted to uppercase
  return val.toUpperCase();
}

See this stackblitz for a demo.

ConnorsFan
  • 70,558
  • 13
  • 122
  • 146
0

I don't know if it's the best way, but without interfering with ng-model directly, I would do like :

import { Component } from '@angular/core';

    @Component({
      selector: 'my-app',
      template: 
        `<input style="text-transform: uppercase" [(ngModel)]="myProperty"> 
        <h1>{{ myProperty }}</h1>
        <h1>{{ _myProperty }}</h1>`,
    })
    export class AppComponent  {
        _myProperty = 'this write in script';
        get myProperty(): string {
            return this._myProperty;
        }
        set myProperty(value: string) {
            this._myProperty = value.toUpperCase();
        }
    }

stackblitz

Crocsx
  • 2,534
  • 1
  • 28
  • 50
0

You can also use (input) event of input field

in .ts

 public value: string = '';

.html

<div>
    <input [value]="value" (input)="value=$event.target.value.toUpperCase()">
</div>
<div>
Value: {{ value }}
</div>

Find useful link from here

https://angular.io/guide/template-syntax#event-binding

Passionate Coder
  • 7,154
  • 2
  • 19
  • 44
0

To write less code, you can use a directive "toUppercase".

You can find the directive here written by spierala.

You can just use it like this (the model will be in uppercase) :

<input type="text" [(ngModel)]="myModel" toUppercase />
A.Baudouin
  • 2,855
  • 3
  • 24
  • 28