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

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

    In the blur event from your input text will changes the value to uppercase

    <input type="text" id="firstName" name="firstName" (blur)="$event.target.value = $event.target.value.toUpperCase()">
    
    0 讨论(0)
  • 2020-11-28 11:21
    <input type="text" oninput="this.value = this.value.toUpperCase()">
    works good in angular to get every symbol to be a big one :)
    
    0 讨论(0)
  • 2020-11-28 11:22

    As @Eric Martinez suggested, you can create a local template variable, and bind the uppercase string to the value property on the input event:

    <input type="text" #input (input)="input.value=$event.target.value.toUpperCase()" />
    

    Alternatively, you can make this a directive:

    @Directive({
        selector: 'input[type=text]',
        host: {
            '(input)': 'ref.nativeElement.value=$event.target.value.toUpperCase()',
        }
    
    })
    export class UpperCaseText {
        constructor(private ref: ElementRef) {
        }
    }
    

    To use the directive, specify UpperCaseText in your component's list of directives:

    directives: [UpperCaseText]
    

    Demo Plnkr

    0 讨论(0)
  • 2020-11-28 11:22

    Simple code without directives

    In the blur event from your Input text call a method that changes the value to upper case, mine is called "cambiaUpper"

    <input id="shortsel" type="text" class="form-control m-b-12" #shortsel="ngModel" name="shortsel" [(ngModel)]="_stockprod.shortName" (blur)="cambiaUpper($event)"/>
    

    And in the component (yourComponentFile.ts) create this method that receives the event, get the value from the event and change this to uppercase.

    public cambiaUpper(event: any) {
          event.target.value = event.target.value.toUpperCase();
    }
    

    Tada!

    0 讨论(0)
提交回复
热议问题