【问题标题】:Operator '>' cannot be applied to types 'string' and 'number' error运算符 '>' 不能应用于类型 'string' 和 'number' 错误
【发布时间】:2021-06-28 06:13:59
【问题描述】:

我在组件 HTML 文件中以角度使用此代码。但是当 ng serve 出现错误时

运算符 '>' 不能应用于类型 'string' 和 'number'

如何解决这个问题

我的 Angular html 代码是

<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>

错误是

错误:src/app/app.component.html:88:17 - 错误 TS2365:运算符“>”不能应用于类型“字符串”和“数字”。

88

18 ; 否则 elseblock"> ~~~~~~~~~~~~

src/app/app.component.ts:9:16 9 模板网址:'./app.component.html', ~~~~~~~~~~~~~~~~~~~~~~ 组件AppComponent的模板出错。

【问题讨论】:

  • 你能显示填充age变量的代码吗?如果来自后端,显示 JSON ?
  • 该代码已经在这里:#age 输入。它只是不完全符合 OP 的预期......
  • @Random:age&lt;input&gt;元素的模板引用变量。

标签: angular angular10


【解决方案1】:

&lt;input&gt; 默认提供字符串类型的值。您可以将其显式转换为数字以执行比较。

<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>

你也可以有type="number",因为年龄必须是一个数字,但如果没有明确的类型转换,它对比较没有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-12
    • 2018-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多