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

后端 未结 10 696
不知归路
不知归路 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:14

    Here is my solution:

    Using host listener to listen input event and then force it to uppercase.

    import {Directive, EventEmitter, HostListener, Output} from '@angular/core';
    @Directive({
      selector: '[ngModel][uppercase]'
    })
    export class UppercaseDirective {
      @Output() ngModelChange: EventEmitter = new EventEmitter();
      value: any;
    
      @HostListener('input', ['$event']) onInputChange($event) {
        this.value = $event.target.value.toUpperCase();
        this.ngModelChange.emit(this.value);
      }
    }
    

    With this directive, you can easily force input to uppercase like this:

    
    

提交回复
热议问题