确保在 Angular8 文本框中输入的任何输入均为大写的正确方法是什么?
我尝试将样式应用于输入标签
文本转换:大写
,但看起来虽然输入框中输入的文本外观是大写的,但实际存储在
[(ng模型)]
不以大写形式显示为大写。
您可以拆分[(ngModel)]为[ngModel]和(ngModelChange),并在事件处理程序中将输入文本转换为大写:
<input [ngModel]="value" (ngModelChange)="value = $event.toUpperCase()" />
Run Code Online (Sandbox Code Playgroud)
但是,当在输入文本的开头或中间插入小写字母时,会出现问题:插入符号自动移动到文本的末尾。本文建议的技术可用于维护插入符位置,如以下改进代码所示:
<input #txt [ngModel]="value" (ngModelChange)="value = convertToUpperCase(txt, $event)" />
Run Code Online (Sandbox Code Playgroud)
public convertToUpperCase(input: HTMLInputElement, val: string) {
// Save caret position
const start = input.selectionStart;
const end = input.selectionEnd;
setTimeout(() => {
// Restore caret position after returning the converted string
input.setSelectionRange(start, end);
});
// Return the input string converted to uppercase
return val.toUpperCase();
}
Run Code Online (Sandbox Code Playgroud)
请参阅此 stackblitz的演示。
| 归档时间: |
|
| 查看次数: |
3413 次 |
| 最近记录: |