Search code examples
javascriptaurelia

Aurelia - Value input depend on another input


I have 2 inputs like this:

HTML

<template>
  Input1
  <textarea name="" value.bind="item.input1" placeholder=""></textarea>

  Input2
  <textarea name="" value.bind="item.input2" placeholder=""></textarea>
</template>

TS FILE

import { MyModel } from '../models/mymodel';
export class MyApp {
    constructor() {
    }

    item: MyModel;

    activate(dto: MyModel) {
        this.item = new MyModel();

    }

}

I want that when I type text in Input1, Input2 will bind to the value from Input1, but when I delete text in Input1, the value in Input2 will not change.

For example:

I type Hello World in Input1 => Input2 value will be: Hello World.

If I change the Input1 value to: Hello => Input2 value will still be: Hello World


Solution

  • You can observe your first input for changes and update the other input if the value got changed to something longer like this:

    import { observable } from "aurelia-binding";
    
    export class MyModel {
      @observable()
      public input1: string;
      public input2: string;
    
      public input1Changed(newValue, oldValue) {
        if (!oldValue || (newValue && newValue.length > oldValue.length)) {
          this.input2 = newValue;
        }
      }
    }
    

    Using the observable decorator, and a convention-named method input1Changed ([property]Changed), you can listen for changes and use the old and new values as you please.