0
votes

I am using this code in angular in component HTML file. But when ng serve then error is showing

Operator '>' cannot be applied to types 'string' and 'number'

How to solve this issue

My angular html code is

<input type="text" #age (keyup)="0" />

<div *ngIf="age.value>18 ; else elseblock">
    You are elegable for vote
</div>

<ng-template #elseblock>
    <div>You are not elegable for vote</div>
</ng-template>

Error is

Error: src/app/app.component.html:88:17 - error TS2365: Operator '>' cannot be applied to types 'string' and 'number'.

88 <div *ngIf="age.value>18 ; else elseblock"> ~~~~~~~~~~~~

src/app/app.component.ts:9:16 9 templateUrl: './app.component.html', ~~~~~~~~~~~~~~~~~~~~~~ Error occurs in the template of component AppComponent.

1
can you show the code filling age variable ? If from backend, show the JSON ?Random
That code is already here: #age on the input. It just doesn't quite do what OP expects ...meriton
@Random: age is the template reference variable of the <input> element.Michael D

1 Answers

2
votes

<input> by default provides values of type string. You could explicitly convert it to a number to perform the comparison.

<input type="text" #age (keyup)="0" />

<div *ngIf="+age.value > 18; else elseblock">     <!-- notice the '+' -->
  You are elegable for vote
</div>

<ng-template #elseblock>
  <div>You are not elegable for vote</div>
</ng-template>

You could also have type="number" since age must be a number but it wouldn't help with the comparison without explicit type casting.