指向大写输入字段 [英] Directive to upper case input fields
问题描述
我想使用指令将所有输入数据转换为大写.为此,我创建了这个自定义指令:
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();
}
}
我这样使用它:
<form [formGroup]="formGroup" appToUpperCase>
几乎可以很好地证明,当我在字段中输入文本时,会保留大写变换,但焦点设置在字段的末尾...因此,当我编辑预填充的输入时,如果要修改数据的开头,我必须在每次Keyup事件之后将焦点设置在正确的位置...
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...
我该如何解决?
推荐答案
我在Angular 7中基于我已阅读的一些帖子,针对大写和小写字母开发了一个解决方案.但是我只测试了反应形式.此解决方案解决了最后一个单词和光标位置的问题.
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.
// user.component.html
<input type="text" name="name" class="form-control" formControlName="name" uppercase />
// user.component.ts
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[uppercase]',
host: {
'(input)': '$event'
}
})
export class UppercaseInputDirective {
lastValue: string;
constructor(public ref: ElementRef) { }
@HostListener('input', ['$event']) onInput($event)
{
var start = $event.target.selectionStart;
var end = $event.target.selectionEnd;
$event.target.value = $event.target.value.toUpperCase();
$event.target.setSelectionRange(start, end);
$event.preventDefault();
if (!this.lastValue || (this.lastValue && $event.target.value.length > 0 && this.lastValue !== $event.target.value)) {
this.lastValue = this.ref.nativeElement.value = $event.target.value;
// Propagation
const evt = document.createEvent('HTMLEvents');
evt.initEvent('input', false, true);
event.target.dispatchEvent(evt);
}
}
}
我在此处发布了 stackblitz
这篇关于指向大写输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!