Angular 在 div 上模糊或在下拉菜单中不调用
Angular blur on div or no called if in a dropdown
我有一个输入,当我输入内容时,我会显示一个 div 和不同的选项(取决于我在输入中输入的内容)。我想在模糊输入时隐藏 div。
<input type="text" (focus)="field.show_options = true" (blur)="field.show_options = false" />
<div *ngIf="field.show_options">
<div *ngFor="let option of field.options" (click)="validate()">
<span>{{ option.label }}</span>
</div>
</div>
如果我点击任何地方,div 就会消失。但是,如果我单击一个选项,div 也会消失,但不会调用来自 onclick 的函数(此处为 validate())。如何管理?
我尝试将 onBlur 事件放在 div 上,但没有工作,即使 tabindex="0"。有什么解决办法吗?
在angular中,你应该使用focusout
而不是blur
:
您可以尝试使用 focusout
而不是 blur
.
<input (focus)="field.show_options = true"
(focusout)="field.show_options = false"
type="text">
除此之外,重要的是要注意 focusout
事件比 click
事件先运行。因此,您需要强制 focusout
在更改值之前稍等片刻。您可以使用打字稿端的方法来做到这一点:
_setFocus(focus: boolean) {
if (!focus) {
// the 200ms here is a matter of trial and error process:
// very uncomfortable, but it's simple
setTimeout(() => (this.field.show_options = focus), 200);
} else {
this.field.show_options = true;
}
}
并且,在您的 HTML 中:
<input (focus)="_setFocus(true)"
(focusout)="_setFocus(false)"
type="text">
就我个人而言,我对代码中的 setTimeout
感到不舒服,但在这种情况下,为了避免它,如果可能的话,它需要更棘手的设置。
我有一个输入,当我输入内容时,我会显示一个 div 和不同的选项(取决于我在输入中输入的内容)。我想在模糊输入时隐藏 div。
<input type="text" (focus)="field.show_options = true" (blur)="field.show_options = false" />
<div *ngIf="field.show_options">
<div *ngFor="let option of field.options" (click)="validate()">
<span>{{ option.label }}</span>
</div>
</div>
如果我点击任何地方,div 就会消失。但是,如果我单击一个选项,div 也会消失,但不会调用来自 onclick 的函数(此处为 validate())。如何管理? 我尝试将 onBlur 事件放在 div 上,但没有工作,即使 tabindex="0"。有什么解决办法吗?
在angular中,你应该使用
您可以尝试使用 focusout
而不是blur
:focusout
而不是 blur
.
<input (focus)="field.show_options = true"
(focusout)="field.show_options = false"
type="text">
除此之外,重要的是要注意 focusout
事件比 click
事件先运行。因此,您需要强制 focusout
在更改值之前稍等片刻。您可以使用打字稿端的方法来做到这一点:
_setFocus(focus: boolean) {
if (!focus) {
// the 200ms here is a matter of trial and error process:
// very uncomfortable, but it's simple
setTimeout(() => (this.field.show_options = focus), 200);
} else {
this.field.show_options = true;
}
}
并且,在您的 HTML 中:
<input (focus)="_setFocus(true)"
(focusout)="_setFocus(false)"
type="text">
就我个人而言,我对代码中的 setTimeout
感到不舒服,但在这种情况下,为了避免它,如果可能的话,它需要更棘手的设置。