Angular 4 HTML中的数学函数无法工作

7

使用以下代码行:

<div class="card light-blue darken-4" [ngClass]="'card-grad-'+Math.floor(Math.random() * 10) + 1">

会报错如下:

ERROR TypeError: Cannot read property 'floor' of undefined

以及 component.ts。

如何解决?

甚至尝试使用decare var Math:any,也尝试在类中定义Math但无果。


3
在组件类中声明 Math = Math 属性。但是不要在模板中使用随机数。你将会收到 Expression has changed after it was checked 的警告。 - yurzui
@yurzui 这正是发生的事情。有什么方法可以让它工作? - Shakti Phartiyal
2个回答

15

在您的component.ts中声明Math:

Math = Math;

或创建一个计算值的函数,并将其绑定到ng-class。


5
尝试像这样做:

尝试像这样做:

<span>{{Math.floor(Math.random() * 10) + 1}}</span>

在你的“.ts”文件中:
Math: any;
Constructor() {
    this.Math = Math;
}

虽然这个表达式会导致以下错误:
Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '6'. Current value: '3'.

但是你仍然可以在模板中使用Math。

请参考下面的链接了解表达式更改错误: https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4

为了摆脱这个错误,你可以在app.module.ts中使用“enableProdMode”。 像下面这样:

import {enableProdMode } from '@angular/core';

export class AppModule {}
enableProdMode();

或者:您可以从angular/core使用"ChangeDetectionStrategy"来实现 import { Component,ChangeDetectionStrategy } from '@angular/core'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, selector: '<selector>', templateUrl: 'template.html', })


尽管採用了您回答的方法,但仍未解决我的问题。尽管控制台没有显示任何错误,但最终得到的类似于以下内容:<div _ngcontent-c4="" class="card light-blue darken-4 card-grad-31"><div _ngcontent-c4="" class="card light-blue darken-4 card-grad-01">这是不正确的,因为该功能应该生成1到10之间的随机数。 - Shakti Phartiyal
嗨,Shakti,那可能是其他问题,因为我只得到了1到10之间的随机数。这是相同的plunk链接:https://plnkr.co/edit/MzuxbNytcLcvGRefTrlT?p=preview - sumit chauhan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接