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

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

问题描述

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

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.

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

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.)

那么,转换 ngControl 使用的值的最佳且低成本的方法是什么?

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

推荐答案

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

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) {
    }
}

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

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

directives: [UpperCaseText]

演示 Plnkr

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

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