Angular - 自动完成效果不佳

问题描述

我在输入 HTML 时遇到 autofocus 问题。当页面加载时,我保存的登录名就会显示出来,并且焦点标记会像之前的图片一样显示在输入的开头。

enter image description here

但是当我在键盘上输入一些东西时,字母会像这样插入到输入的末尾:

enter image description here

我试图修复它,但没有成功。我想在输入的末尾或开头有焦点的标记,但工​​作正常。

我使用的是 angular 11

我的代码

<input autofocus [(ngModel)]="usuario.name" type="text" name="name" id="name" placeholder="Insira o login">

解决方法

autofocus 属性有问题。发生这种情况是因为您的输入值是在输入焦点之后出现的。

您应该使用 focus 使用 ViewChild 函数,并在数据到来后将焦点放在 input 上。为了实现这一点:

constructor() {}

@ViewChild('myname') input: ElementRef;
...
private someFunction(): void {
  // Data is loaded using service
  this.input.nativeElement.focus(); // now focus
}
,

我解决了像这样禁用自动完成的情况:

<input autocomplete="new-password" [(ngModel)]="usuario.password" type="password" name="senha" id="senha" placeholder="Insira a senha">

现在用户需要选择保存的密码。谢谢各位。