Control value of input in Aurelia

試著忘記壹切 提交于 2019-12-04 14:06:43

You can subscribe to the input's keydown event and prevent the default action when it's a character you don't want to appear in the input.

Here's an example of using this approach to build a very simple numeric input: https://gist.run?id=3101e8f73cf4da32445505d0e4258f01

app.html

<template>
  <require from="./numeric-input"></require>

  <numeric-input value.bind="value"></numeric-input>

  ${value}
</template>

app.js

export class App {
  value = '';
}

numeric-input.html

<template>
  <input type="text" value.bind="value" placeholder.bind="placeholder">
</template>

numeric-input.js

import {
  inject,
  bindable,
  bindingMode
} from 'aurelia-framework';

// http://stackoverflow.com/a/995193/725866
function isNavigationOrSelectionKey(e) {
  // Allow: backspace, delete, tab, escape, enter and .
  if ([46, 8, 9, 27, 13, 110, 190].indexOf(e.keyCode) !== -1 ||
    // Allow: Ctrl+A/X/C/V, Command+A/X/C/V
    ([65, 67, 86, 88].indexOf(e.keyCode) !== -1 && (e.ctrlKey === true || e.metaKey === true)) ||
    // Allow: home, end, left, right, down, up
    (e.keyCode >= 35 && e.keyCode <= 40)) {
     // let it happen, don't do anything
     return true;
  }
  return false;
}

// http://stackoverflow.com/a/995193/725866
function keydown (e) {
  if (isNavigationOrSelectionKey(e)) {
    return;
  }
  // If it's not a number, prevent the keypress...
  if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
    e.preventDefault();
  }
}

@inject(Element)
export class NumericInput {
  @bindable({ defaultBindingMode: bindingMode.twoWay }) value;
  @bindable placeholder = '';

  constructor(element) {
    this.element = element;
  }

  attached() {
    this.element.addEventListener('keydown', keydown);
  }

  detached() {
    this.element.removeEventListener('keydown', keydown);
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!