【发布时间】:2019-11-25 06:39:57
【问题描述】:
我需要创建一个指令,将所有表单的输入字段格式化为大写..
我已经这样做了:
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[uppercaser]'
})
export class UperCaserDirective {
lastValue: string;
constructor(public ref: ElementRef) {
}
@HostListener('input', ['$event']) onInput(event) {
const resEventValue = event.target.value.toUpperCase();
if (!this.lastValue || (this.lastValue && event.target.value.length > 0 && this.lastValue !== resEventValue)) {
this.lastValue = this.ref.nativeElement.value = resEventValue;
const evt = document.createEvent('HTMLEvents');
evt.initEvent('input', false, true);
event.target.dispatchEvent(evt);
}
}
}
但是这个只适用于一个输入字段...
我想这样做以最小化我必须放在每个输入字段中的别名...
我需要使用 DIRECTIVE,尽可能少地重复
【问题讨论】: