简体   繁体   中英

Cast $event.target to HTMLInputElement within Angular's HTML template

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.

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;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM