1

From within a template's input element, I wish to pass $event.target's value to an onChange() function.

<input (input)="onChange($event.target?.value)">

This leads to an error: Property 'value' does not exist on type 'EventTarget'.ngtsc(2339). My thoughts are that $event.target by default has an EventTarget type and should be somehow cast to HTMLInputElement type, but I can't find a way to achieve this. All examples I've found suggest to pass $event itself and make a cast within a component's code. Disabling or lowering strictness is also not an option for me. Is there a way to set type directly within a template?

Thanks in advance.

2
  • 1
    Why would you try to cast from the template when its perfectly fine to do it from your ts file? Commented Feb 10, 2022 at 23:23
  • Well, to be honest, I don't have a strong reason, except from it's done that way in a course I'm using to learn Angular, but they don't use strict mode and I do. Commented Feb 10, 2022 at 23:28

1 Answer 1

2

Passing $event is a dubious practice!

use a template reference variable to get the user's input. It's easier to get to the input data with the template reference variable than to go through the $event object.

@Component({
  selector: 'app-component',
  template: `
    <input #myInput (input)="onChange(myInput.value)">
  `
})
export class AppComponent {
   values = '';
   onChange(value: string) {
      this.values += value;
   }
}
Sign up to request clarification or add additional context in comments.

4 Comments

This answer is wrong for multiple reasons. First, the input event itself passes $event, you can just choose to pass it completely or extract just the value from it. There is no reason to consider this wrong or dubious (in fact, in many cases you might want to have the complete event object available rather than just the value). Secondly, in an event callback you should use the value of the passed event object (event.target.value), NOT the value from the input directly (myInput.value).
@paddotk the answer is completely correct. If you don't familiar with Angular framework then I highly recommend to read the following documentation: angular.io/guide/user-input#passing-event-is-a-dubious-practice
What I think is meant by that section is an explanation for their choice of implementation; i.e. that event.target is not recognized as an HTMLInputElement, hence the required cast to this type.
@paddotk ofc it's their choice of implementation. His question is related to Angular framework not pure JS or other frameworks. So, My answer leads him to use template reference variable. anyway, I think you should upvote to my answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.