我需要在输入上模拟焦点事件以打开NgbTypeahead下拉菜单,这可能吗?因为我无法做到:
.ts:
@ViewChild('inputExecutor') inputExecutor: ElementRef
focus$ = new Subject<string>();
click$ = new Subject<string>();
focused(){
this.executorForm.controls['executor'].setValue('');
this.focus$.next(this.executorForm.value.executor);
}
inputFocus(){
this.inputExecutor.nativeElement.focus();
}
html:
<input
class="choose-executor-input"
type="text"
name="executor"
formControlName="executor"
[ngbTypeahead]="searchExecutors"
(focus)="focus$.next($event.target.value); focused()"
(click)="click$.next($event.target.value);"
(selectItem)="itemSelected($event)"
[resultFormatter]="formatExecutors"
[inputFormatter]="formatExecutors"
#instance="ngbTypeahead"
#inputExecutor/>
<button
click)="inputFocus()"
class="btn btn-executor-open"></button>
</button>
那么我如何专注于输入以打开下拉菜单?有什么问题吗?
答案 0 :(得分:0)
要实现此目的,您可以在NgbTypeahead绑定到的输入元素上触发输入事件,然后调用focus方法,以便输入具有焦点,您可以立即开始输入。
我从ng-bootstrap网站的Open on focus演示开始,进行了以下更改:
声明一个新的模板变量elem
,以便在组件TS文件中可以访问DOM元素(请注意,您不能使用现有的instance
,因为它是NgbTypeahead而不是HTML元素):< / p>
组件HTML:
<input
id="typeahead-focus"
...
#instance="ngbTypeahead"
#elem
/>
组件TS:
@ViewChild('elem') elem: ElementRef;
在模板中添加一个按钮,该按钮将调用焦点功能-单击该按钮将打开快捷键并专注于该按钮:
<button (click)="openTypeahead()">Open Typeahead</button>
在组件TS文件中添加一个openTypeahead
函数,如下所示:
public openTypeahead(): void {
// Dispatch event on input element that NgbTypeahead is bound to
this.elem.nativeElement.dispatchEvent(new Event('input'));
// Ensure input has focus so the user can start typing
this.elem.nativeElement.focus();
}
请参阅this Stackblitz进行演示
答案 1 :(得分:0)
我用
HTML:
<input #instance="ngbTypeahead" .../>
<button (click)="openTypeahead(instance)">Open Typeahead</button>
TS:
openTypeahead(inp) {
inp._elementRef.nativeElement.value = '';
inp._elementRef.nativeElement.dispatchEvent(new Event('input'));
inp._elementRef.nativeElement.focus();
}