Wednesday, April 11, 2018

Get out of using any to fish out event.target.value in a (change) event in an Angular 4 application.

If you have a control like so:

<input type="text" (change)="updateField($event)" />

 
 

You are probably used to doing this:

whatsInTheBox(event: any) {
   const content = event.target.value;
   alert(content);
}

 
 

But, you could do this instead:

whatsInTheBox(event: Event) {
   const control = <HTMLInputElement>event.target;
   const content = control.value;
   alert(content);
}

 
 

Note that you cannot dot dot dot out to event.target.value with an Event. You have to cast HTMLInputElement, also, this seemed to work when tabbing away with a KeyboardEvent which is one of many events that implements Event per this but I wondered if when I clicked away instead of tabbing away if I should be using MouseEvent. It seemed to work, the mousing elsewhere with KeyboardEvent, but I wonder if that is just because type safety is all a placebo in TypeScript. Anyhow, if both things inherit from Event why not just use Event if Event has .target hanging off it?

No comments:

Post a Comment