Angular 2表:如何使用键盘箭头切换案例

时间:2017-01-31 19:14:12

标签: javascript angular typescript

我是网络开发的新手。我正在使用Angular 2创建一个Sudoku Web应用程序。我已经实现了该表。但是,我无法使用键盘箭头浏览它。

这是app.component.html

<body>
<div class="container">
 <div class="col-sm-6">
   <table >
             <tr *ngFor="let row of cases" class='row'> 
             <td *ngFor="let case of row" class='case'><input type="text" maxlength="1" arrowSelector>
             </td>
             </tr>

  </table>
 </div>

<div class="col-sm-6">
    <h3>Chronometre: 11:32</h3>

</div>
<div class="col-sm-2">

    <button type="button" class="btn btn-primary btn-block">Nouvelle partie</button>
    <button type="button" class="btn btn-default btn-block">Réinitialiser partie</button>


</div>
<div class="col-sm-6">
    <h3>Niveau de difficulté</h3>
    <button type="button" class="btn btn-success">Facile</button>
    <button type="button" class="btn btn-warning">Moyen</button>
    <button type="button" class="btn btn-danger">Difficile</button>
</div>

这是app.component.ts:

import { Component } from '@angular/core';

import {ArrowSelectorDirective} from './arrowSelector.directive'



@Component({

  selector: 'my-app',

  templateUrl: 'app/app.component.html',

  directives : [arrowSelector],

 })

export class AppComponent {

  cases: number[][];



  constructor(){

this.cases =[];

for(var i: number =0; i<9;i++){

  this.cases[i] = [];

  for(var j: number=0; j<9;j++){

    this.cases[i].push(1);

  }

}

  }

 }

我想我必须写一个指令文件,但我不确定它是否是解决方案或如何做。

谢谢

1 个答案:

答案 0 :(得分:0)

这是一个plunker,其中箭头导航通过输入字段。

您可以像这样实现箭头键导航:

HTML:

<table>
    <tr *ngFor="let row of field; let i = index;">
        <td *ngFor="let column of row; let n = index;"><input [focus]="i === rowPos && n === columnPos" style="width: 50px; height: 50px;" (keyup)="onKey($event)" ></td>
    </tr>
</table>

打字稿:

onKey($event){
  let keyCode = $event.keyCode;

  if (keyCode === 37) { //left arrow
    this.columnPos -= 1;
    if (this.columnPos < 0) this.columnPos = 8;
  }else if (keyCode === 38) { //up arrow
        this.rowPos -= 1;
        if (this.rowPos < 0) this.rowPos = 8;
  }else if (keyCode === 39) { //right arrow
        this.columnPos += 1;
        if (this.columnPos > 8) this.columnPos = 0;
  }else if (keyCode === 40) { //down arrow
        this.rowPos += 1;
        if (this.rowPos > 8) this.rowPos = 0;
  }
}

输入字段的焦点通过指令解决。

import {Directive, Input, ElementRef} from '@angular/core';

@Directive({
    selector: '[focus]'
})

export class FocusDirective {
    @Input()
    focus:boolean;

    constructor(private element: ElementRef) {}

    protected ngOnChanges() {
      if (this.focus)
        this.element.nativeElement.focus();
    }

}