2

I'm trying to go through the Adam Freeman angular book, but many of the example don't work, I imagine due to new changes since it was written.

The issue I have is the following template doesn't work due to typescript not liking the event.target

<input type="text" class="form-control" (input)="selectedProduct=$event.target.value">

enter image description here

The selectedProduct is declared in the template component as show below (

export class ProductComponent {
    selectedProduct: string = "";
}

I then tried this by casting it as a HTMLTextAreaElement but then it says possibly undefined

enter image description here

I also tried with the !

enter image description here

If anyone could explain how I get this to work that would be great as it seems like pulling teeth, cheers.

3 Answers 3

3

Use $any() type cast function.

Try this:

  <input type="text"  class="form-control" (input)="selectedProduct=$any($event).target.value">
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this at least worked, much appreciated, the next part of the book goes into using [(ngModel)] which then means I dont have to do this, but useful to get it working, cheers.
2

This issues is not about angular and it's about typescript. This feature is called strict null checks and you can turn it off by strictNullChecks to false in tsconfig file.

But better way is to use Optional chaining (see this) that is a means to access properties on possibly null or undefined reference.

Note that you need typescript version be 3.7 or later for Optional chaining:

<input type="text" class="form-control" (input)="selectedProduct=$event?.target?.value">

1 Comment

Thanks I believe I am using this 3.7 as that is what is installed in this path C:\Program Files (x86)\Microsoft SDKs\TypeScript\3.7 but the ? still cause the issue "Property 'value' does not exist on type 'EventTarget'."
0

Late response but this is the simplest solution in my opinion:

<input type="text"  class="form-control" (input)="selectedProduct=selection.value" #selection>

Comments

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.