Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing input field value without ngModel in Angular2/Typescript

I'm using Typescript with Angular2, just like in the Angular2 Tour of Heroes tutorial.

I have an input field that I want to attach a change event to, so that some custom logic can perform when the field is changed. I need to know the field's current value to perform the logic, so I don't want to bind that field with ngModel, as that will override the property before I'm able to retrieve its former value before it was changed.

So I have something like:

<input (change)="handleChange(myObj, $event)" value={{ myObj.myField }}... />

Then in handleChange:

handleChange (obj: MyObjectClass, e: Event) {
  oldValue: number = obj.myField;
  newValue : number = parseInt(e.target.value);

  // Do some logic

  obj.myField = newValue;
}

While this works fine in code, the Typescript compiler is throwing an error error TS2339: Property 'value' does not exist on type 'EventTarget'. on the line newValue : number = parseInt(e.target.value);

Is there a better way of doing this?

like image 899
A. Duff Avatar asked Mar 11 '23 09:03

A. Duff


2 Answers

To do validation on input values, you are better off writing a custom validator instead of trying to use change event. That being said, you can pass the input value by using a reference to the input like this:

<input #myInput (change)="handleChange(myInput.value, $event)" value={{ myObj.myField }}... />
like image 54
Ben Richards Avatar answered Apr 30 '23 04:04

Ben Richards


If you see the definition of EventTarget, it is like below,

 interface EventTarget {
   addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
   dispatchEvent(evt: Event): boolean;
   removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
 }

it does not contain the value property. so if you want to do it in right way you can use ,

 e.target['value']

Now the reason why there is no value proerty on EventTarget can to support different type of events , for e.g you may use same Event for input type checked and in that case you would like to see checked property.

like image 37
Madhu Ranjan Avatar answered Apr 30 '23 05:04

Madhu Ranjan