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.
CodePudding user response:
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;
}
}