How to Convert Input Value to Uppercase in Angular 2 (Value Passing to Ngcontrol)

Typescript + Html: How to force uppercase in an input field

You can simply add oninput="this.value = this.value.toUpperCase()" in your <input> tag and it will instantly convert any input in your input field to Uppercase.

Angular 2 Directive to set input field to uppercase using ngModelChange

You should be using a directive as below,

@HostListener('keyup') onKeyUp() {
this.el.nativeElement.value = this.el.nativeElement.value.toUpperCase();

}

LIVE DEMO

Angular 2 | Showing lowercase value when form is submitted

The angular form control listens to the 'input' event of the element. It seems your directive does the same but after the directive updates the value, ngControl doesn't know about it till the next input event happens. So at the end of the data the form control always have the value entered . You can dispatch an 'input' event from the directive but I doubt it will go in a loop. You can try listening to keydown/keyup event or something directive and emitting 'input' event after that.

When directives are used with form controls I think it is better to extend ControlValueAccessor for your directive. Please see some of the answers to the question below for some good examples :-

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

Automatically convert entered letters into capital [Angular]

While binding the expression in view you can use toUpperCase() function

Try this

<hello name="{{name.toUpperCase() }}"></hello>    
<input type="text" [(ngModel)]="name">

Here is the working solution

using directive to capitalize input

I found it, as I was doing it I was changing the value in model but not in input, the solution:

constructor(private el: ElementRef) {  }

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

Make input field default to lowercase in angular

the following in the html file:

<input type="text" [ngModel]="_textValue" (ngModelChange)="ConvertToLower($event)">

and the following code in component.ts file:

_textValue:string;
ConvertToLower(evt) {
this._textValue = evt.toLowerCase();
}


Related Topics



Leave a reply



Submit