Html 如何在 angular 2 中将输入值转换为大写(传递给 ngControl 的值)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35826325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert input value to uppercase in angular 2 (value passing to ngControl)
提问by ankitkamboj
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 在 angular 2 中的值来验证输入字段。我需要验证用户是否始终以大写形式输入值。
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 而不是 ngModel 处理来自输入字段的值(考虑到我可以使用 ngModelChange 事件将值更新为大写。)
So what is the best and low cost way to convert the value used by ngControl.
那么什么是转换 ngControl 使用的值的最佳和低成本的方法。
回答by pixelbits
As @Eric Martinez suggested, you can create a local template variable, and bind the uppercase string to the value property on the input event:
正如@Eric Martinez 建议的那样,您可以创建一个本地模板变量,并将大写字符串绑定到输入事件的 value 属性:
<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:
要使用该指令,请UpperCaseText
在组件的指令列表中指定:
directives: [UpperCaseText]
回答by subaru710
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<any> = 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:
使用此指令,您可以轻松地将输入强制为大写,如下所示:
<input type="text" class="form-control" placeholder="ID"
formControlName="id" [(ngModel)]="form.value.id" uppercase/>
回答by Thierry Templier
I would create a custom implementation of ControlValueAccessor. The latter would correspond to a directive that would listen the input event of the host. This way you will be able to put in uppercase what you user fills. The control will automatically contains the value in uppercase.
我将创建 ControlValueAccessor 的自定义实现。后者将对应于监听主机输入事件的指令。通过这种方式,您将能够将用户填写的内容大写。该控件将自动包含大写的值。
Here is the implementation:
这是实现:
@Directive ({
selector: 'input[uppercase]',
// When the user updates the input
host: { '(input)': 'onChange($event.target.value.toUpperCase())' }
})
export class UppercaseValueAccessor extends DefaultValueAccessor {
(...)
// When the code updates the value of the
// property bound to the input
writeValue(value:any):void {
if (value!=null) {
super.writeValue(value.toUpperCase());
}
}
}
Don't forget to register this custom value accessor in the directive providers. This way your custom value accessor will be used instead of the default one.
不要忘记在指令提供程序中注册这个自定义值访问器。这样,您的自定义值访问器将被使用而不是默认访问器。
const UPPERCASE_VALUE_ACCESSOR = new Provider(NG_VALUE_ACCESSOR, { useExisting: forwardRef(() => UppercaseValueAccessor), multi: true});
@Directive ({
providers: [ UPPERCASE_VALUE_ACCESSOR ],
(...)
})
export class UppercaseValueAccessor ...
And add the directive in the directives attribute of the component where you want to use this approach.
并在要使用此方法的组件的指令属性中添加指令。
See this class for more details:
有关更多详细信息,请参阅此类:
This link could give additional hints (see section "NgModel-compatible component):
此链接可以提供其他提示(请参阅“NgModel 兼容组件”部分):
回答by superjos
At least in my experience, I found two of the answers here insightful, but not working on their own: from Thierry Templier(with first comment as well), and from cal.
至少根据我的经验,我发现这里的两个答案很有见地,但不是独立工作的:来自 Thierry Templier(还有第一条评论)和来自 cal。
I put together parts of both, and came up with this version, which is now working with Angular 4.1.1 in a reactive form:
我将两者的部分放在一起,并提出了这个版本,它现在以反应形式与 Angular 4.1.1 一起使用:
import { Directive, Renderer, ElementRef, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR, DefaultValueAccessor } from '@angular/forms';
const LOWERCASE_INPUT_CONTROL_VALUE_ACCESSOR = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => LowerCaseInputDirective),
multi: true,
};
@Directive({
selector: 'input[lowercase]',
host: {
// When the user updates the input
'(input)': 'onInput($event.target.value)',
'(blur)': 'onTouched()',
},
providers: [
LOWERCASE_INPUT_CONTROL_VALUE_ACCESSOR,
],
})
export class LowerCaseInputDirective extends DefaultValueAccessor {
constructor(renderer: Renderer, elementRef: ElementRef) {
super(renderer, elementRef, false);
}
writeValue(value: any): void {
const transformed = this.transformValue(value);
super.writeValue(transformed);
}
onInput(value: any): void {
const transformed = this.transformValue(value);
super.writeValue(transformed);
this.onChange(transformed);
}
private transformValue(value: any): any {
const result = value && typeof value === 'string'
? value.toLowerCase()
: value;
return result;
}
}
This is for lower-case, but everything holds for upper-case as well, just rename directive, replace within selector
and transformValue
.
这是小写的,但一切都适用于大写,只需重命名指令,替换内selector
和transformValue
。
Edit:
A straightforward usage example from HTML code using such directive:
编辑:
使用此类指令的 HTML 代码中的简单用法示例:
<input id="myField"
formControlName="myField"
type="text" class="form-control required"
lowercase>
回答by KIA
pixelbitshas 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
pixelbits提供了一个很好的解决方案,但它在最新版本的 Angular (v4.3.1) 中不起作用,因为指令从组件中贬值。我的解决方案仅基于他的回答,但适用于最新的
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 :
大写.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 组件。
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: `
<div>
<h2>Hello {{name}}</h2>
Auto Capitalize True: <input [UpperCase]="true" type="text" #input />
<br/>
Auto Capitalize False: <input [UpperCase]="allowEdit" type="text"/>
</div>
`,
})
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 Plnkrwhich demonstrate this.
这是一个证明这一点的Plnkr。
回答by Денис Баланчук
<input type="text" oninput="this.value = this.value.toUpperCase()">
works good in angular to get every symbol to be a big one :)
回答by Hemant Sharma
Here is my working code i am using angular4
这是我使用 angular4 的工作代码
This is your directive for upper case
这是您的大写指令
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appUpper]'
})
export class UpperDirective {
constructor(public ref: ElementRef) { }
@HostListener('input', ['$event']) onInput(event) {
this.ref.nativeElement.value = event.target.value.toUpperCase();
}
}
This is your html file code where you used uppercase directive
这是您使用大写指令的 html 文件代码
<input type="text" id="id" placeholder="id" tabindex="0" formControlName="id" appUpper>
回答by Cal
Here's my more generic solution which is basically like DefaultValueAccessor with a text "transformer" function added. So you would use
这是我更通用的解决方案,它基本上类似于 DefaultValueAccessor 并添加了文本“转换器”功能。所以你会使用
<input mdInput [transformer]="uppercase" ...>
In your compontent you have the uppercase function (you could do other things beside uppercase like implement a mask)...
在您的组件中,您具有大写功能(除了大写之外,您还可以做其他事情,例如实现掩码)...
uppercase(value: string) {
return value.toUpperCase();
}
Directive...
指示...
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
import { Directive, forwardRef, Input, OnChanges, SimpleChanges, Renderer, ElementRef } from '@angular/core';
import { TextMaskModule, MaskedInputDirective } from 'angular2-text-mask';
@Directive({
selector: 'input[transformer]',
// When the user updates the input
host: { '(input)': 'handleInput($event.target.value)', '(blur)': 'onTouched()' },
providers: [
{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TextTransformerDirective), multi: true },
]
})
export class TextTransformerDirective implements ControlValueAccessor {
private inputElement: HTMLInputElement
lastValue = "";
onTouched = () => { }
onChange = (_: any) => { }
@Input('transformer')
transformer = (v: string) => v;
constructor(private renderer: Renderer, private element: ElementRef) {
}
handleInput(value: any) {
let newVal = this.transformer(value);
if (newVal != value || this.lastValue != newVal) {
this.lastValue = newVal;
this.renderer.setElementProperty(this.element.nativeElement, 'value', newVal);
this.onChange(newVal);
}
}
writeValue(value: any) {
let normalizedValue = value == null ? '' : value;
normalizedValue = this.transformer(normalizedValue);
this.renderer.setElementProperty(this.element.nativeElement, 'value', normalizedValue);
}
registerOnChange(fn: (value: any) => any): void { this.onChange = fn }
registerOnTouched(fn: () => any): void { this.onTouched = fn }
}
回答by Axel Osorio
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"
在输入文本的模糊事件中,调用一个将值更改为大写的方法,我的称为“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.
并在组件 (yourComponentFile.ts) 中创建此接收事件的方法,从事件中获取值并将其更改为大写。
public cambiaUpper(event: any) {
event.target.value = event.target.value.toUpperCase();
}
Tada!
多田!
回答by Puneet Sehgal
In the blur
event from your input
text will changes the value to uppercase
如果blur
您的input
文本中的值将更改为大写
<input type="text" id="firstName" name="firstName" (blur)="$event.target.value = $event.target.value.toUpperCase()">