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.
2 Answers
Reset to default 15Declare 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',
})
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