enhance keyboard navigation with answers

This commit is contained in:
Baptiste Lemoine 2019-11-23 16:05:44 +01:00
parent e179be812e
commit 9c02b1ae2b
2 changed files with 29 additions and 12 deletions

View File

@ -14,9 +14,11 @@
type="text"
class="answer"
[(ngModel)]="answer.text"
(keyup.enter)="addAnswer()"
(keyup)="navigateOrDelete($event,i)"
placeholder="réponse"
>
<button (click)="config.answers.splice(i,1)">X</button>
<button class="btn btn--alert" (click)="config.answers.splice(i,1)">X</button>
</li>
</ol>

View File

@ -1,4 +1,4 @@
import {ChangeDetectorRef, Component, Inject, OnInit} from '@angular/core';
import {AfterViewInit, ChangeDetectorRef, Component, Inject, OnInit} from '@angular/core';
import {BaseComponent} from '../base-page/base.component';
import {ConfigService} from '../../config.service';
@ -9,7 +9,7 @@ import {DOCUMENT} from '@angular/common';
templateUrl: './answers.component.html',
styleUrls: ['./answers.component.scss']
})
export class AnswersComponent extends BaseComponent implements OnInit {
export class AnswersComponent extends BaseComponent implements OnInit, AfterViewInit {
private answerList = [];
@ -24,6 +24,10 @@ export class AnswersComponent extends BaseComponent implements OnInit {
ngOnInit() {
}
ngAfterViewInit() {
this.focusOnAnswer(0)
}
trackFunction(index: number, item: any): number {
return item.id;
}
@ -35,19 +39,30 @@ export class AnswersComponent extends BaseComponent implements OnInit {
text: ''
});
this.cd.detectChanges(); // to refresh the view before focusing on the new input
this.focusOnAnswer(this.config.answers.length - 1)
}
focusOnAnswer(i) {
const AnswersDomToFocus = this.document.querySelectorAll('.answers .answer');
const dom = AnswersDomToFocus[AnswersDomToFocus.length - 1];
const dom = AnswersDomToFocus[i];
if (dom.focus) {
dom.focus();
}
if (dom.select) {
dom.select();
}
}
// add a new answer on the press of ENTER in an input
addWhenEnterKey(event) {
navigateOrDelete(event: KeyboardEvent, i) {
console.log('event', event);
if (event.keyCode === 13) {
this.addAnswer();
if (event.ctrlKey && event.key == "d") {
this.config.answers.splice(i, 1)
}
if (event.key == "ArrowUp" && i > 0) {
this.focusOnAnswer(i - 1);
}
if (event.key == "ArrowDown" && i < this.config.answers.length) {
this.focusOnAnswer(i + 1);
}
return;
}
}