如何指定事件以仅触发Angular2中的某些击键

时间:2016-03-07 22:20:22

标签: angular

所有

我对Angular2很新,说我有一个输入框,我想只在某些字符输入时触发一个事件,来自Angular2 BASICS" User Input"部分:有一个例子:

@Component({
  selector: 'key-up3',
  template: `
    <input #box (keyup.enter)="values=box.value">
    <p>{{values}}</p>
  `
})
export class KeyUpComponent_v3 {
  values='';
}

此代码仅响应&#34;输入&#34;关键笔划,我想知道如何指定其他关键笔划,我的意思是有像keyup.a,keyup.b ......等等

谢谢

1 个答案:

答案 0 :(得分:5)

(keyup.a)应该有效。 (我在Chrome中进行了测试,但它确实有效)。

我找到了以下&#34;文档&#34;在github上关于这个&#34;功能&#34;:https://github.com/angular/angular/commit/8fa1539bacd454635d1f78ab056e2017929d0634

feat(keyEvents): support for <div (keyup.enter)="callback()">
This commit adds a plugin for the event manager, to allow a key name to
be appended to the event name (for keyup and keydown events), so that
the callback is only called for that key.

Here are some examples:
 (keydown.shift.enter)
 (keyup.space)
 (keydown.control.shift.a)
 (keyup.f1)

Key names mostly follow the DOM Level 3 event key values:
http://www.w3.org/TR/DOM-Level-3-Events-key/#key-value-tables
There are some limitations to be worked on (cf details
in #1136) but for now, this
implementation is reliable for the following keys (by "reliable" I mean
compatible with Chrome and Firefox and not depending on the keyboard
layout):
- alt, control, shift, meta (those keys can be combined with other keys)
- tab, enter, backspace, pause, scrolllock, capslock, numlock
- insert, delete, home, end, pageup, pagedown
- arrowup, arrowdown, arrowleft, arrowright
- latin letters (a-z), function keys (f1-f12)
- numbers on the numeric keypad (but those keys are not correctly simulated
by Chromedriver)

There is a sample to play with in examples/src/key_events/.