How to convert input value to uppercase in angular 2 (value passing to ngControl)

Viewed 101998

I am trying to validate the input fields using ngControl's value in angular 2. i need to validate that the user enters the value in upper case always.

Now we need to convert the value entered by user to uppercase. But i am handling values from input fields using ngControl, not ngModel ( considering i could have used ngModelChange event to update value to uppercase.)

So what is the best and low cost way to convert the value used by ngControl.

10 Answers
<input type="text" oninput="this.value = this.value.toUpperCase()">
works good in angular to get every symbol to be a big one :)

In the blur event from your input text will changes the value to uppercase

<input type="text" id="firstName" name="firstName" (blur)="$event.target.value = $event.target.value.toUpperCase()">

Simple code without directives

In the blur event from your Input text call a method that changes the value to upper case, mine is called "cambiaUpper"

<input id="shortsel" type="text" class="form-control m-b-12" #shortsel="ngModel" name="shortsel" [(ngModel)]="_stockprod.shortName" (blur)="cambiaUpper($event)"/>

And in the component (yourComponentFile.ts) create this method that receives the event, get the value from the event and change this to uppercase.

public cambiaUpper(event: any) {
      event.target.value = event.target.value.toUpperCase();
}

Tada!

Here is my working code i am using angular4

This is your directive for upper case

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[appUpper]'
})
export class UpperDirective {

  constructor(public ref: ElementRef) { }

  @HostListener('input', ['$event']) onInput(event) {
    this.ref.nativeElement.value = event.target.value.toUpperCase();
  }

}

This is your html file code where you used uppercase directive

<input type="text" id="id" placeholder="id" tabindex="0" formControlName="id" appUpper>
Related