0

Okay so I'm currently trying to set the color value of an <input type="color"> via [value] using a function inside the TS of the component like this:

HTML

<input type="color"  [value]="getRandomColor()" title="Choose your color">

TS

export class FiltersComponentComponent implements OnInit {

  constructor() { }
  getRandomColor() {
      var letters = '0123456789ABCDEF';
      var color = '#';
      for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }

  ngOnInit(): void {
  }

}

The thing is that the random color is setted, but its getting setted in a never ending loop, so every frame the color is getting refreshed. I've tried to replicate the error in a StackBlitz but there it simply works! Here it is. This is the error the console gives me on my project :

core.js:5980 ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: '#60B9D1'. Current value: '#84DFC7'.

Any idea?

  • 2
    We've had similar issues with some controller methods being reevaluated every change detection cycle. We solved it by creating a small indirection. create a property on your controller to bind instead and set its value using the function internally so that the function is not referenced in your template. That worked for us in these edge-cases. – Mikkel Christensen Sep 03 '21 at 08:58
  • Does this answer your question? [Expression \_\_\_ has changed after it was checked](https://stackoverflow.com/questions/34364880/expression-has-changed-after-it-was-checked) – Yong Shun Sep 03 '21 at 08:59
  • @MikkelChristensen yea i tried that and worked, the thing is that I want to create a whole bunch of values on a ngFor. I guess i will have to make an array, just wanted to avoid that. – Sebastian Ciocarlan Sep 03 '21 at 09:04
  • 1
    try to mark your component as ChangeDetetionStrategy.OnPush. should be less change detections on this component. however colors would still change when you interact with input – Andrei Sep 03 '21 at 09:18
  • @Andrei It is indeed working after I changed the ChangeDetectionStrategy to onPush! Actually is just working as intended! Try to write it as a response so I can mark it as working! – Sebastian Ciocarlan Sep 03 '21 at 09:42

1 Answers1

1

try to mark your component as ChangeDetetionStrategy.OnPush.

It should be then less change detections on this component. however colors would still change when you interact with input, or inputs of your component are changed

Andrei
  • 10,117
  • 13
  • 21