angular - html:21:40 - 错误 TS2362:算术运算的左侧必须是“any”、“number”、“bigint”类型或枚举类型
问题描述
HTML
<star-rating
value="{{(res.popularity| number : '1.0-0') /20 }}"
totalstars="{{totalstar}}"
checkedcolor="yellow"
uncheckedcolor="black"
size="24px"
readonly="true"
(rate)="onRate($event)"
></star-rating>
如图所示,我有很多问题。有人可以解释一下这个问题吗
解决方案
正如迈克尔 D 在上面的评论中所说, DecimalPipe (又名 | 数字)将数字转换为字符串,因此您无法将其进一步传递给数字类型的 @Input() 。
您可以为您的项目以一种干净且可重用的方式修复它,即创建一个自定义管道,该管道接受一个表示小数的字符串并将其转换为“数字”类型。就是这样:
as-number.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'asNumber',
pure: false
})
export class AsNumberPipe implements PipeTransform {
transform(value: string): unknown {
return parseFloat(value);
}
}
不要忘记在app.module.ts
文件中声明它(或您将要使用它的功能模块):
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AsNumberPipe } from './pipes/as-number.pipe';
@NgModule({
declarations: [
AppComponent,
AsNumberPipe
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
现在你可以像这样在你的 html 模板中使用它:
<star-rating
value="{{(res.popularity | number : '1.0-0' | asNumber) / 20 }}"
totalstars="{{totalstar}}"
checkedcolor="yellow"
uncheckedcolor="black"
size="24px"
readonly="true"
(rate)="onRate($event)"
></star-rating>
奖金:
根据我在您的错误转储中看到的内容,您还有一些与 StarRating 组件的其他两个输入绑定相关的错误。
totalstars="{{totalstar}}"
//错误:类型“字符串”不可分配给类型“数字”。
要解决此问题,您可以使用我们在上面创建的相同管道,如下所示:
totalstars="{{totalstar | asNumber}}"
readonly="true"
// 错误:类型 'string' 不可分配给类型 'boolean'。
为此,您只需要通过用尖括号包装属性来确保您确实将“true”作为布尔值传递:
[readonly]="true"
所以最后你的html标签看起来像这样:
<star-rating
value="{{(res.popularity | number : '1.0-0' | asNumber) / 20 }}"
totalstars="{{totalstar | asNumber}}"
checkedcolor="yellow"
uncheckedcolor="black"
size="24px"
[readonly]="true"
(rate)="onRate($event)"
></star-rating>
推荐阅读
- javascript - 如何在 vuejs 中构建一些包含 .vue 文件的文件夹?
- reactjs - 如何修复 npx create-react-app 错误?
- java - 如何在 Android 上定义圆形 ImageView?
- angular - 400 错误请求“将值 {null} 转换为类型‘System.Int32’时出错。路径‘id’,第 1 行,位置 10。” POST 请求
- reactjs - React WordPress Customizer 自定义控件
- javascript - onsubmit 返回 false 后表单提交按钮不起作用
- c# - 防止从c#中的字符串类继承的原因是什么?
- android - 是否可以在相同的活动/android 片段布局中拥有 React Native 和 Android 视图?
- python - 根据 pandas 中的列查找最小值
- python - Android Studio中没有为模块配置python解释器