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

ankitkamboj picture ankitkamboj · Mar 6, 2016 · Viewed 77.3k times · Source

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.

Answer

pixelbits picture pixelbits · Mar 6, 2016

As @Eric Martinez suggested, you can create a local template variable, and bind the uppercase string to the value property on the input event:

<input type="text" #input (input)="input.value=$event.target.value.toUpperCase()" />

Alternatively, you can make this a directive:

@Directive({
    selector: 'input[type=text]',
    host: {
        '(input)': 'ref.nativeElement.value=$event.target.value.toUpperCase()',
    }

})
export class UpperCaseText {
    constructor(private ref: ElementRef) {
    }
}

To use the directive, specify UpperCaseText in your component's list of directives:

directives: [UpperCaseText]

Demo Plnkr