-1

I am trying to assign a random color to the div background using the below example

Random Color

But facing below error:

Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

You can check-in console of created stackblitz.

I have already tried the below answers:

  1. How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime
  2. Expression ___ has changed after it was checked

But no luck! Can anyone please look into this and help?

Razneesh
  • 1,147
  • 3
  • 13
  • 29
Pathik Vejani
  • 4,263
  • 8
  • 57
  • 98

1 Answers1

2

One solution for this is to use a directive.

So I created a directive called appRandomColor

Here's the code for it.

import {Directive, ElementRef, Input, OnInit} from '@angular/core';

@Directive({
  selector: '[appRandomColor]'
})
export class RandomColorDirective implements OnInit {

  constructor(private element: ElementRef) { }

  ngOnInit() {
      this.element.nativeElement.style.color = this.getRandomColor();
  }

  getRandomColor() {
    var color = Math.floor(0x1000000 * Math.random()).toString(16);
    return '#' + ('000000' + color).slice(-6);
  }
}

And added it to declarations in AppModule

Then I applied it to the *ngFor loop. And no errors.

<ul>
    <li class="hero" *ngFor="let hero of heroes" appRandomColor>
      {{ hero }}
    </li>
</ul>

Screenshot with the result wanted by the user

I suggest reading more about Angular Change Detection because it will help you understand these errors more. Here are some articles that I find very helpful

Edit

On Component.ts

colorsArray = ['#FF5733', '#DA4323', '#FFB1A0', '#BB523C', '#BB2505', '#DE4922'];

On Component.html

 <li class="hero" *ngFor="let hero of heroes" [appRandomColor]="colorsArray">
      {{ hero }}
 </li>

To add predefined colors array to directive


@Input('appRandomColor') colors: string[]; 

ngOnInit() {
   this.element.nativeElement.style.color = colors[Math.floor(Math.random() * colors.length)]; 
} 

Enea Jahollari
  • 148
  • 2
  • 4