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

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

    pixelbits has provided a great solution but it does not work in the latest version of Angular (v4.3.1) as directives are depreciated from component. My solution is based on his answer only but works with the latest

    I am providing a generic solution with custom attribute directive with a boolean input which will covert the input to Uppercase if it is true.

    upper-case.directive.ts :

         import { Directive, ElementRef, Input } from '@angular/core';
         @Directive({
         selector: '[UpperCase]',
         host: {
            '(input)': 'toUpperCase($event.target.value)',
    
         }
    
        })
        export class UpperCaseTextDirective  {
    
        @Input('UpperCase') allowUpperCase: boolean;
        constructor(private ref: ElementRef) {
        }
    
        toUpperCase(value: any) {
            if (this.allowUpperCase)
            this.ref.nativeElement.value = value.toUpperCase();
        }
    
        }
    

    Here is the corresponding App component with the template.

    app.ts

        //our root app component
       import {Component, NgModule, VERSION} from '@angular/core'
       import {BrowserModule} from '@angular/platform-browser'
       import {UpperCaseTextDirective} from './upper-case.directive'
    
        @Component({
        selector: 'my-app',
        template: `
        

    Hello {{name}}

    Auto Capitalize True:
    Auto Capitalize False:
    `, }) export class App { name:string; allowEdit:boolean; constructor() { this.name = `Angular! v${VERSION.full}`; this.allowEdit= false; } } @NgModule({ imports: [ BrowserModule ], declarations: [ App,UpperCaseTextDirective ], bootstrap: [ App ] }) export class AppModule {}

    Here is a Plnkr which demonstrate this.

提交回复
热议问题