2016-09-21 27 views
0

我們需要開發盲文語言的教程應用程序。更新鍵盤事件的輸入值 - Angular2

我們有一個輸入,當用戶在文檔準備就緒的時候按下「df」,我們需要將輸入的值更新爲「b」。

<input type="text" [value]="letter" readonly> 

export class ExercisesComponent { 

letter:string; 

constructor(private router: Router, private exerciseService: ExerciseService, private route: ActivatedRoute) {} 


ngOnInit(): void { 
    this.showKey(); 
} 

showKey(event: any) { 
    let map = {}; 
    self = this; 
    onkeydown = onkeyup = function(e){ 
     e = e || event; 
     map[e.keyCode] = e.type == 'keydown'; 
     if(map[68] && map[70]) { 
      console.log('Keypress D + F '); 
      self.letter = 'b' // Should print letter 'b' in input 
     } 
    } 
} } 

當我們按下「d + f」時,我們需要以雙向綁定的實時模式更新輸入值。

只有當我們專注於輸入和離開焦點狀態時,以上代碼纔會將輸入值更新爲「b」。

UPD:這是一個Plunker演示:https://plnkr.co/edit/Xqotggv4xjk5jgsaVHYS?p=preview

問題是,當鍵盤事件在實時模式下被觸發,我們可以如何更新此值?

回答

1

試試這個:

map = {}; 
@HostListener('document:keyup', ['$event']) 
@HostListener('document:keydown', ['$event']) 
keUp(e) { 
    this.map[e.keyCode] = e.type == 'keydown'; 
    if(this.map[68] && this.map[70]) { 
    console.log('Keypress D + F '); 
    this.letter = 'b' // Should print letter 'b' in input 
    } 
} 

Plunker Example