0

I'm sure I'm just doing something stupid but I can't see it.

I have the following html:

<input type="number" (change)="changeEventDate(event, dateField.value)" [value]="date" #dateField />

And typescript:

const date: number;

...

changeEventDate(event: Event, date: number) {
  console.log(typeof date); // This logs "string"
}

}

So I'm passing in a number to [value], it's an input of type number and the typescript method takes in a number parameter... how is it still a string?

(I know can just cast it to fix the issue, but I'm trying to understand why it's not working as expected.)

And I guess, in case it's important:

"@angular-devkit/build-angular": "~0.803.20",
"@angular/cli": "~8.3.20",
"@angular/compiler-cli": "~8.2.14",
"@angular/language-service": "~8.2.14",
"typescript": "~3.5.3"
2
  • the input value is always string do like this (change)="changeEventDate(event, +dateField.value)" Commented Dec 11, 2019 at 18:56
  • can you try this : (change)="changeEventDate($event, $event.target.value)" Commented Dec 11, 2019 at 19:58

2 Answers 2

2

By using the dateField.value you will be getting the DOM value, which will always be a string.

There are couple things you can do to make things better, First thing (best thing in Angular) which is two way data binding.

  • make your date variable public and then in your html <input [(ngModel)]="date" ...
  • And in your function console.log(typeof this.date);

Another thing (just a workaround), is to keep your code as is, and just convert the passed in value to a number console.log(typeof Number(date));

Sign up to request clarification or add additional context in comments.

Comments

0

Here you're getting the value from input field dateField.value it returns the string value. You can fix it changing to changeEventDate(event, +dateField.value)

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.