2017-01-11 9 views
3

を追加することなく、私は私のアプリケーションでキーボードショートカットを追加している、およびそれらのいずれかは、例えば、特定の入力にフォーカス方式をトリガシフト + Fあります私の検索フィールド。フォーカステキスト入力は、キー押下値

input-elementはコンポーネントツリーのどこにでも置くことができます。私のアプローチはEventEmitterとそれを聴取するディレクティブでサービスを使用することです。

@Component({ .. }) 
export class SomeComponent { 
    @HostListener('document:keypress', ['$event']) 
    onKeyDown(event: KeyboardEvent) { 
    if (event.shiftKey) { 
     let key = event.key; 
     if (key === 'F') { 
     this.focusService.focus('mySearchBox'); 
     } 
    } 
    } 

    constructor(private focusService: FocusService) { } 
} 

SomeComponentは、どこかのhtmlで私が焦点ディレクティブを適用します。

<input focus="mySearchBox"> 

FocusDirective

@Directive({ 
    selector: '[focus]' 
}) 
export class FocusDirective implements AfterViewInit { 
    @Input() focus: string; 

    constructor(
     private elementRef: ElementRef, 
     private focusService: FocusService) { } 

    ngAfterViewInit() { 
     this.focusService.focusSource.subscribe(res => { 
      this.setFocus(res); 
     }); 
    } 

    setFocus(item: string) { 
     // I use strings to match the call with the input 
     if (this.focus === item) { // 'mySearchBox' === 'mySearchBox 
      this.elementRef.nativeElement.focus(); 
      // Do something to avoid the keypress event 
     } 
    } 
} 

FocusService

@Injectable() 
export class FocusService { 
    focusSource = new EventEmitter<string>(); 

    focus(string) { 
    this.focusSource.emit(string); 
    } 
} 

問題

私はカリフォルニア州の場合ll focusService.focus( 'mySearchBox)それは動作しますが、私はキーボードイベントを待ち受けているので、フォーカスが設定され、Fが入力値にに追加されます。

入力がキー押しを無視するように、何らかの形でこの動作を回避することができますか?

私は入力の値をリセットしようとしましたが、メソッドが終了した後にFが追加されるため、使用されません。

答えて

0

preventDefault()を使用してみてください:

let key = event.key; 
if (key === 'F') { 
    event.preventDefault(); 
    this.focusService.focus('mySearchBox'); 
} 

event.preventDefault()メソッドが起こってからの要素のデフォルトの動作を停止します。

続きを読むpreventDefault()hereを参照してください。

編集:

あなたは​​イベントの代わりkeypressに耳を傾ける必要がある場合があります。

@HostListener('keydown', ['$event']) 
+1

これは、ありがとう! –

関連する問題