Search code examples
angularkeyboardangular-ngmodel

Update input value on keyboard event - Angular2


We need to develop tutorial app for braille language.

We have an input, when user keypress "df" on document ready, we need to update value of input to "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
        }
    }
}  }

When we press "d+f" we need to update input value in real time mode with two way binding.

This code above will update input value to "b", only when we focused to input and leave focus state.

UPD: Here is a Plunker demo: https://plnkr.co/edit/Xqotggv4xjk5jgsaVHYS?p=preview

Question is how we can update this value when keyboard event was triggered in real time mode?


Solution

  • Try this:

    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