[英]Focus angular material input on clicking tilde
我在組件“ awesomebar.component.html ”中有一個角材料輸入,例如:
<input #placeAutocompleteInput style="max-width:100%;"
[placeholder]="placeholderText"
[matChipInputFor]="chipListPlaces"
[formControl]="mainSearchCtrl"
[matAutocomplete]="mainAutocomplete"
(keyup.enter)="onEnter($event)"/>
我定義了一個角度指令,以在單擊另一個文件keyboard.directive.ts中的 tilde(〜)時突出顯示輸入元素。 當我從鍵盤上單擊(〜)時,輸入元素應突出顯示。
我的指令代碼:
@HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) {
if(event.keyCode === 192)
{
// input focus logic
this.placeAutocompleteInput.nativeElement.focus();
this.placeAutocompleteInput.nativeElement.value = '';
}
}
我無法在以上邏輯中獲得placeAutocompleteInput.nativeElement。 我如何使它工作。 由於輸入元素在另一個組件文件中,並且指令在另一個文件中定義,因此我無法訪問nativeElement。
編輯: 通過以下調整得到答案 :
在文件awesomebar.component.html中:
<input #placeAutocompleteInput style="max-width:100%;"
[placeholder]="placeholderText"
[matChipInputFor]="chipListPlaces"
[formControl]="mainSearchCtrl"
[matAutocomplete]="mainAutocomplete"
(keyup.enter)="onEnter($event)"
captureDoubleTilde/>
在文件keyboard.directive.ts中:
@Directive({
selector: `[captureDoubleTilde]`
})
export class CaptureDoubleTildeDirective {
constructor(
public dialog: MatDialog,
private el: ElementRef
) { }
@HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) {
if(event.keyCode === TILDE_KEYCODE && localStorage.accessToken != undefined) {
pressCount += 1;
var focus= 0;
if (pressCount >1) {
var scrollStep = -window.scrollY / (50 / 15),
scrollInterval = setInterval(function(){
if ( window.scrollY != 0 ) {
window.scrollBy( 0, scrollStep );
}
else clearInterval(scrollInterval);
},15);
this.el.nativeElement.focus();
this.el.nativeElement.value = '';
}
setTimeout(() => pressCount=0, 200);
}
}
}
但是,當我雙擊波浪號時,輸入中會顯示高亮(〜)字符,我該如何糾正它。
在這里,我編輯了DEMO 。 所有這些都應用於相同級別的組件和指令,但是您可以將它們拆分並用於更高級別,還可以將TestService添加到app.module provider數組並導入它。
這是什么this.placeAutocompleteInput
? 這是您指令中的摘要嗎? 如果是,並且將其應用於輸入,則應通過ElementRef訪問指令的主機來使其工作 :
import {ElementREf} ...
constructor(private elR: ElementRef){}
@HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) {
if(event.keyCode === 192)
{
// input focus logic
this.elR.nativeElement.focus();
this.elR.nativeElement.value = '';
}
}
ps我也想知道,如果按下鍵,為什么需要focus()
-它不是已經聚焦了嗎?
在這里您可以看到一個DEMO 。 我更改了幾個事件,但是想法是一樣的。 單擊space
和焦點將被刪除,並且輸入的值也為空字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.