html:21:40 - 错误 TS2362:算术运算的左侧必须是“any”、“number”、“bigint”或枚举类型 as-number.pipe.ts

问题描述

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>

我有很多问题,如图所示。谁能解释一下这个问题

enter image description here

解决方法

正如 Michael 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 组件的其他两个输入绑定相关的错误。

  1. totalstars="{{totalstar}}" // 错误:“字符串”类型不能分配给“数字”类型。

要解决此问题,您可以使用我们在上面创建的相同管道,如下所示:

totalstars="{{totalstar | asNumber}}"
  1. 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>