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.
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]
Here is my solution:
Using host listener to listen input event and then force it to uppercase.
import {Directive, EventEmitter, HostListener, Output} from '@angular/core';
@Directive({
selector: '[ngModel][uppercase]'
})
export class UppercaseDirective {
@Output() ngModelChange: EventEmitter<any> = new EventEmitter();
value: any;
@HostListener('input', ['$event']) onInputChange($event) {
this.value = $event.target.value.toUpperCase();
this.ngModelChange.emit(this.value);
}
}
With this directive, you can easily force input to uppercase like this:
<input type="text" class="form-control" placeholder="ID"
formControlName="id" [(ngModel)]="form.value.id" uppercase/>
<input type="text" oninput="this.value = this.value.toUpperCase()">
works good in angular to get every symbol to be a big one :)