如何在角度2中将输入值转换为大写(传递给ngControl的值) [英] How to convert input value to uppercase in angular 2 (value passing to ngControl)

查看:208
本文介绍了如何在角度2中将输入值转换为大写(传递给ngControl的值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用角度为2的ngControl值来验证输入字段。
我需要验证用户始终以大写形式输入值。

现在我们需要将用户输入的值转换为大写。但我使用ngControl处理输入字段的值,而不是ngModel(考虑到我可以使用ngModelChange事件将值更新为大写)。

那么什么是最好的和最低的这是昂贵的方法来转换ngControl使用的值。

解决方案

正如@Eric Martinez所建议的,您可以创建一个本地模板变量,并将大写字符串绑定到输入事件:

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

或者,您可以将其作为指令:

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

})
导出类UpperCaseText {
构造函数(private ref:ElementRef ){
}
}

要使用指令,请指定 UpperCaseText 在你的组件的指令列表中:

 指令:[UpperCaseText] 

演示程序Plnkr


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 to convert the value entered by user to uppercase. But i am handling values from input fields using ngControl, not ngModel ( considering i could have used ngModelChange event to update value to uppercase.)

So what is the best and low cost way to convert the value used by ngControl.

解决方案

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

这篇关于如何在角度2中将输入值转换为大写(传递给ngControl的值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆