Search code examples
angulartypescriptangular-forms

Angular set input on change equal to a variable holding a function


I know you can do something like

<input (input)="doSomething($event)" />
<input (input)="boolVar = $event.target.value > 5" />

but how can I do something like

funcVar = (e) => {
  console.log(e.target.value)
}

<input (input)="funcVar" />

I tried other things like

<input [input]="funcVar" />
<input [(input)]="funcVar" />

but no luck. Reason I'm doing this is that our forms are being generated from a data set, so they only way I can add on stuff like is by passing in stuff through variables that will generate the forms.


Solution

  • The event handler should call the function. The markup would be:

    <input (input)="funcVar($event)" />
    

    for the funcVar member defined as:

    public funcVar = (e) => {
      console.log(e.target.value)
    }
    

    If another method is assigned to funcVar later, that new method will be executed when the input event is triggered:

    someMethodExecutedLater() {
      this.funcVar = (e) => {
        // From now on, this new function will be called by the event handler
        ...
      }
    }