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
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()">
<input type="text" oninput="this.value = this.value.toUpperCase()">
works good in angular to get every symbol to be a big one :)
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
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!