【问题标题】:How to autocapitalize the first character in an input field only when the mouse click out side using directives in AngularJS?仅当鼠标在AngularJS中使用指令单击时,如何自动将输入字段中的第一个字符大写?
【发布时间】:2019-08-11 22:29:18
【问题描述】:

在输入文本时它会是小写,但是当鼠标移开时,第一个字母必须变为大写。

【问题讨论】:

  • 你能展示一下试过的代码吗?
  • 我是角度新手
  • 你在使用响应式表单吗?还是您使用普通的旧模板驱动表单(使用 ngmodel)?
  • 那就试试吧! This 是 onBlur 事件,this 用于 AutoCaptalize 指令

标签: angular


【解决方案1】:

我假设您没有使用响应式表单。不需要单独的指令,因为您需要做的就是处理焦点输出事件。基本上,您可以将focusout 事件绑定到您的输入。聚焦后,trigger() 方法将被触发。

在您的 component.html 上,

<input class="form-control" (focusout)="trigger($event)" [(ngModel)]="sampleInput" type="text">

在您的 component.ts 上,trigger() 方法将第一个字母转换为大写。然后,我们将转换后的字符串分配给您的模型 (sampleInput)

sampleInput: string = undefined;
.
.
trigger(event) {
  const inputValue = event.target.value;
  const result = inputValue.charAt(0).toUpperCase() + inputValue.slice(1);
  this.sampleInput = result;
}

但是,在一个不太相关的注释中,我个人最喜欢的是通过纯 CSS 来处理它。但是,当然,这个解决方案有一些限制,因为它将字符串中每个单词的第一个字母大写(例如,'hi john' -> 'Hi John'),而不是整个字符串的第一个字母。这种方法的一个明显优点是不会改变该字符串的基础值,因为只有“显示”受到影响。

input {
  text-transform: capitalize;
}

【讨论】:

    猜你喜欢
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 2014-08-02
    • 2015-07-24
    • 2016-02-01
    • 1970-01-01
    相关资源
    最近更新 更多