【问题标题】:Form - Directive to format all inputs to uppercaseForm - 将所有输入格式化为大写的指令
【发布时间】: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,尽可能少地重复

【问题讨论】:

    标签: angular angular-directive


    【解决方案1】:
    <input id="name" data-upper type="text"/>
    <input id="middle" data-upper type="text"/>
    <input id="sur" data-upper type="text"/>
    

    在具有属性的动态创建的元素上增加文本 上以及何时发生 keyup 操作

    $(document.body).on('keyup', '[data-upper]', function toUpper() {
      this.value = this.value.toUpperCase();
    });
    

    否则,您可以使用管道。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-10
    • 2018-03-31
    • 2017-11-12
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    相关资源
    最近更新 更多