How to convert input value to uppercase in angular 2 (value passing to ngControl)

后端 未结 10 688
不知归路
不知归路 2020-11-28 10:31

I am trying to validate the input fields using ngControl\'s value in angular 2. i need to validate that the user enters the value in upper case always.

Now we need

10条回答
  •  醉梦人生
    2020-11-28 11:05

    Here's my more generic solution which is basically like DefaultValueAccessor with a text "transformer" function added. So you would use

    
    

    In your compontent you have the uppercase function (you could do other things beside uppercase like implement a mask)...

      uppercase(value: string) {
        return value.toUpperCase();
      }
    

    Directive...

    import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
    import { Directive, forwardRef, Input, OnChanges, SimpleChanges, Renderer, ElementRef } from '@angular/core';
    import { TextMaskModule, MaskedInputDirective } from 'angular2-text-mask';
    
    @Directive({
      selector: 'input[transformer]',
      // When the user updates the input
      host: { '(input)': 'handleInput($event.target.value)', '(blur)': 'onTouched()' },
      providers: [
        { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TextTransformerDirective), multi: true },
      ]
    
    })
    export class TextTransformerDirective implements ControlValueAccessor {
      private inputElement: HTMLInputElement
      lastValue = "";
      onTouched = () => { }
      onChange = (_: any) => { }
      @Input('transformer')
      transformer = (v: string) => v;
    
      constructor(private renderer: Renderer, private element: ElementRef) {
    
      }
    
      handleInput(value: any) {
        let newVal = this.transformer(value);
        if (newVal != value || this.lastValue != newVal) {
          this.lastValue = newVal;
          this.renderer.setElementProperty(this.element.nativeElement, 'value', newVal);
          this.onChange(newVal);
        }
      }
    
      writeValue(value: any) {
        let normalizedValue = value == null ? '' : value;
        normalizedValue = this.transformer(normalizedValue);
        this.renderer.setElementProperty(this.element.nativeElement, 'value', normalizedValue);
      }
    
      registerOnChange(fn: (value: any) => any): void { this.onChange = fn }
    
      registerOnTouched(fn: () => any): void { this.onTouched = fn }
    
    }
    

提交回复
热议问题