when I run my code, price.value
says I can't do it like that, but it was done before. and I get a mistake like this.
Argument of type 'string' is not assignable to parameter of type 'number'.
<div class="form-group">
<label for="price">price</label>
<input #price type="text" class="form-control" name="price" />
</div>
<div class="form-group">
<div class="custom-control custom-checkbox">
<input
#isactive
type="checkbox"
class="custom-control-input"
id="isActive"
/>
<label for="" class="custom-control-label" for="isActive"></label>
</div>
what do I have to do to get the values in the input form. my Button codes are defined below.
<button
class="btn btn-primary"
(click)="
addProduct(name.value, price.value, isactive.checked);
name.value = '';
price.value = '';
isactive.checked = false
"
>
I get an error like this and use version angular 11. as far as I can remember, it was working on version 9.
Argument of type 'string' is not assignable to parameter of type 'number'.
addProduct(name.value, **price.value**, isactive.checked);*>
my addProduct function is here
addProduct(name: string, price: number, isactive: boolean) {
console.log(name);
console.log(price);
console.log(isactive);
}
The Value of an input field is by default a string. So you have to cast it before you put it into your function with
addProduct(name.value, parseInt(price.value), isactive.checked)
Change the type of parameter price
to string. Then inside the function use parseInt
or Number
to convert the string to number.
addProduct(name: string, price: string, isactive: boolean) {
const pr = parseInt(price,10);
if(!isNaN(pr){
// rest of code her
}
}
If you call the function like this addProduct(name.value, parseInt(price.value), isactive.checked)
and if parseInt(price.value)
is not a number, the function will throw an error as addProduct
is expecting price.value
to be a number.
For example if price.value is string like 'testString' then parseInt(testString)
will be NaN
Use this:
<!-- bad code -->
<input #price type="text" class="form-control" name="price" />
<!-- good code -->
<input #price type="number" class="form-control" name="price" />
Change the input type to number.
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.