最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Math function not working in angular 4 HTML - Stack Overflow

programmeradmin3浏览0评论

Using the following line :

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

gives the following error:

ERROR TypeError: Cannot read property 'floor' of undefined

and component.ts.

How to resolve it ?

Even tried using decare var Math:any and also tried defining Math in the class but in vain.

Using the following line :

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

gives the following error:

ERROR TypeError: Cannot read property 'floor' of undefined

and component.ts.

How to resolve it ?

Even tried using decare var Math:any and also tried defining Math in the class but in vain.

Share Improve this question asked Jan 25, 2018 at 19:19 Shakti PhartiyalShakti Phartiyal 6,2543 gold badges27 silver badges46 bronze badges 2
  • 3 Declare Math = Math property in component class. But don't use random in template. Expression has changed after it was checked will wait you – yurzui Commented Jan 25, 2018 at 19:24
  • @yurzui that is exactly what is happening. Any way to get it working ? – Shakti Phartiyal Commented Jan 25, 2018 at 20:05
Add a comment  | 

2 Answers 2

Reset to default 15

Declare the Math in your component.ts

Math = Math;

or create a function that would calculate your value and bind that to ng-class

Try something like this:

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

In your ".ts" file :

Math: any;
Constructor() {
    this.Math = Math;
}

This expression although will lead you to
Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '6'. Current value: '3'.

Still you can use Math in your template.

See below link for the expression changed error: https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4

To get rid of that error you can user "enableProdMode" in app.module.ts. Like below:

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

export class AppModule {}
enableProdMode();

Or: use can use "ChangeDetectionStrategy" from angular/core import { Component, ChangeDetectionStrategy } from '@angular/core'; @Component({ changeDetection: ChangeDetectionStrategy.OnPush, selector: '<selector>', templateUrl: 'template.html', })

发布评论

评论列表(0)

  1. 暂无评论