I want to use a directive to transform all input data to uppercase. To achieve that, I create this custom directive :
@Directive({
selector: '[appToUpperCase]'
})
export class ToUpperCaseDirective {
constructor() {}
@HostListener('input', ['$event']) onKeyUp(event) {
event.target['value'] = event.target['value'].toUpperCase();
}
}
And I use it like that :
<form [formGroup]="formGroup" appToUpperCase>
It works almost good exept that when I enter text in my field, the upper case transform is permormed but the focus is set at the end of the field...So when I edit a pre filled input, if I want to modify the begining of the data, I have to set the focus at the right place after each Keyup event...
How can I fix that ?
Pankaj's idea it's better than create a directive. You only must send data.toUpperCase(). Anyway if you want use a directive like this. Be careful, not only we must use preventDefault(), we must dispatch event change
I developed a solution in Angular 7 for uppercase and lowercase, based in some posts i've read. But i tested only for reactive forms. This solution resolve the problem of the last word and the position of the cursor.
I posted here in stackblitz
Basically when you modify the value from imperative code, it becomes difficult manage position of cursor. When you re-write value input value, it throws cursor at the start of input.
I'd recommend you to go for CSS way. More cleaner