How To Show One Random Background Color For Each Record In A Html Table
Solution 1:
It's happening, because Angular runs change detection each time you move your mouse. When change detection happens, Angular executes all functions which are bound in the template.
For this reason (performance bottleneck), it is not recommended to bind functions to templates. You can read more about it here and here.
Now for the actual solution, here is a description of the approach.
Because it is not a quick solution, I cannot post the full code here, so you will need to use these suggestions to do the implementation. If you are stuck somewhere or don't know some of the points (e.g. how to create a pipe), post separate questions or search.
Instead of generating a random colour, the idea would be to generate a colour for each cell based on a value in the table cell. This way, you can use a pipe to get the colour code based on a specific input:
- Instead of
[ngStyle]="getRandomColor()"
you would do something like this:[style.background]="cellValue | getRandomColor"
.
Here, cellValue
would be the actual cell value (or it can also be a row number or any other predefined value you have available), and getRandomColor
is the pipe you need to create.
- Create the pipe. The logic for the pipe can be adopted from here.
This way, the background colour would be set based on the value of the cell. And you will not run into the change detection issue as you have now.
Post a Comment for "How To Show One Random Background Color For Each Record In A Html Table"