1

I need to create a directive that format all form´s input field to uppercase..

I already did this:

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);
    }
  }

}

But this one works only for an one input field...

I wanna do this to minimize the alias that I have to put inside each of input fields...

I need with DIRECTIVE, to repeat as little as possible

LeoHenrique
  • 229
  • 5
  • 16

1 Answers1

0
<input id="name" data-upper type="text"/>
<input id="middle" data-upper type="text"/>
<input id="sur" data-upper type="text"/>

Upper the text on a dynamically created element which has an attribute upper and when keyup action happens

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

Otherwise, you can use a pipe for that.

Kishan Patel
  • 778
  • 11
  • 26
  • I need to do with directive – LeoHenrique Jul 16 '19 at 13:57
  • Indeed, it's weird to use jQuery for this.. :-s – johey Jul 16 '19 at 14:19
  • This question is similar and seems to have good answers: https://stackoverflow.com/questions/46825078/directive-to-upper-case-input-fields – johey Jul 16 '19 at 14:21
  • @johey, i got my code from this one: https://stackoverflow.com/a/53156582/10647645, so i already tried this answers and dont understand how I can use on my form... – LeoHenrique Jul 16 '19 at 17:44
  • The harder point is, I want to do this in my form tag and all inputs inside get uppercase – LeoHenrique Jul 16 '19 at 17:45
  • 1
    @heavyrick posted a link to a stackblitz demo: https://stackblitz.com/edit/angular-form-uppercase-lowercase You just need to add the attribute uppercase on your form or your input element (it appears to work on both levels). So you'll want something like
    – johey Jul 17 '19 at 18:19
  • @johey - This worked perfectly, thank you very much. – LeoHenrique Jul 17 '19 at 19:04
  • Im thinking something impossible, but I need to make sure if it's impossible... Thinking like old desktop apps where we have global parameters like with my exemple here: to convert all of fields to uppercase, have a way to do this in angular? Like text field uppercase, select items uppercase (all items, but on db is lowercase), things like that? – LeoHenrique Jul 18 '19 at 16:28