我希望你能帮我解决这个错误。
Chrome浏览器打印此跟踪:
error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
39 <div ngSwitch="{{e%2}}">
这是我的"app.component.html">:
<mat-list role="list">
<mat-list-item role="listitem" *ngFor="let e of lista; let i = index">
{{i + 1}}::{{e}} -
<div ngSwitch="{{e%2}}">
<div *ngSwitchCase="0" [ngClass]="'impar'">impar</div>
<div *ngSwitchCase="1" [ngClass]="'par'">par</div>
<div *ngSwitchDefault="0">Sin resultados.</div>
</div>
<button mat-stroked-button color="accent" (click)="remover(i)">Remover</button>
<mat-divider></mat-divider>
</mat-list-item>
</mat-list>
其他信息:
- TS:"~4.5.2">
- Angular CLI:13.1.2
- 节点:16.13.1
- 程序包管理器:npm 8.1.2
- 操作系统:win32 x64
OBS:如果我用加号(+(代替模运算符(%(,它编译得令人满意。
虽然问题中没有提供lista
的类型,但它似乎是string[]
类型,可能类似于:
lista = ['0', '1']
如果是这种情况,那么在尝试执行{{e%2}
时会出现错误,因为模运算符不能用于字符串操作数。其他运营商如-
、*
也是如此。
现在,+
之所以有效,是因为当与字符串一起使用时,它会执行串联。
您可以通过将插值写入{{+e%2}}
来克服错误,前提是它始终是字符串中的有效数字,否则您将获得NaN
。