Issue
createCharge() {
let a = ((document.getElementById('amount') as HTMLInputElement).value);
let b = ((document.getElementById('prescription') as HTMLInputElement).value);
let c = ((document.getElementById('vision') as HTMLInputElement).value);
let d = ((document.getElementById('clinic') as HTMLInputElement).value);
let e = ((document.getElementById('dental') as HTMLInputElement).value);
let t = parseFloat(a) + parseFloat(b) + parseFloat(c) + parseFloat(d) + parseFloat(e);
if (a <= t) {
alert('total amount should less than ' + this.charge.amount);
return false;
}
this is my code from ts file. this is working but its showing error. while compiling.
this is the error which i am facing:
error TS2365: Operator '<=' cannot be applied to types 'string' and 'number'.
Solution
In your code, a is a string and t is a number. To compare them you would need to write
if (parseFloat(a) <= t)
I would highly recommend you revise your code to not use the native document object and its query methods. It's bad practice for Angular. Using a form would be a much better option. It would make cleaner more readable code (and much less of it). But if you dont want to include a form, the 'angular way' would be something like the following:
In the template
<input type=text #amount />
<input type=text #prescription />
<input type=text #vision />
<input type=text #clinic />
<input type=text #dental />
In the component, make sure to import ViewChild and ElementRef
import { Component, ViewChild, ElementRef, ... }
Then add these declarations to your component
@ViewChild('amount') amount : ElementRef;
@ViewChild('prescription') prescription : ElementRef;
@ViewChild('vision') vision : ElementRef;
@ViewChild('clinic') clinic : ElementRef;
@ViewChild('dental') dental : ElementRef;
And revise your method to something like the following :
createCharge() {
let t = 0;
const chargeTypes = ['amount', 'prescription', 'vision', 'clinic', 'dental'];
chargeTypes.forEach( type => { t += parseFloat(this[type].value) });
if (parseFloat(this.amount.value) <= t) {
alert('total amount should less than ' + this.charge.amount);
return false;
}
}
You'll notice there's a lot of redundant code in my example - this is why people use forms! A form would eliminate the need for the redundant ViewChild declarations, as you could access the values of all the different elements from a single form object.
Answered By - diopside
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.