GrkEngineer GrkEngineer - 1 month ago 6
AngularJS Question

Aurelia version of Angular's ng-change

I'm porting over an Angular app to Aurelia as a learning exercise, and I wasn't sure how to recreate the Angular ng-change behavior.

There is a element which when changed fires off a javascript callback. I'm not sure how to do this in Aurelia. Or should I just be using the HTML5 ?

Answer

To bind a method/expression to an event, use event.delegate="expression", replacing "event" with the actual event name like change or input.

Here's an example: https://gist.run?id=a3ced6a08842a421a715c7df068b41d5

app.html

<template>
  <form change.delegate="changeCount = changeCount + 1"
        input.delegate="incrementInputCount($event.target)">
    <p>
      This form has changed ${changeCount} times.
      The input event has fired ${inputCount} times.
    </p>
    <input type="text" placeholder="type something...">
    <input type="text" placeholder="type something...">
    <input type="text" placeholder="type something...">
  </form>
</template>

app.js

export class App {
  changeCount = 0;
  inputCount = 0;

  incrementInputCount(inputElement) {
    console.log(inputElement.value);
    this.inputCount++;
  }
}

Note: if the event doesn't bubble (eg focus/blur), use event.trigger and put the binding directly on the element that will fire the event. For example, <input blur.trigger="doSomething()">.

Comments