如何在html表中为每个记录显示一种随机的背景色 [英] how to show one random background color for each record in a html table

查看:55
本文介绍了如何在html表中为每个记录显示一种随机的背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用角度版本8.在我的应用程序中,我必须为html表中的每个记录显示随机颜色.但是当显示随机颜色时,如果我在显示页面中移动光标,则每次移动颜色都会改变,并且我看到很多新颜色用于单记录.有人可以建议如何在html表中为一条记录显示一种随机颜色吗.

I am using angular version 8. In my application i have to show a random color for each record in html table. but when displaying the random color if i move the cursor in display page, for each movement the color changing and i am seeing a lot of new colors for single record. Can any one suggest that how to show one random color for one record in html table.

这是我的代码.

getRandomColor() {
      let letters = '0123456789ABCDEF';
      let color = '#';
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      const styles = {
        'background-color' : color,
        'padding':"27px",
        "border-radius":"100%",
        "color":"white"
      };
      return styles;
    }

 <span  [ngStyle]="getRandomColor()">V</span>

推荐答案

它正在发生,因为每次移动鼠标时Angular运行更改检测.发生更改检测时,Angular将执行模板中绑定的所有功能.

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.

因为这不是一种快速的解决方案,所以我无法在此处发布完整的代码,因此您将需要使用这些建议来执行实现.如果您被困在某处或不了解某些要点(例如,如何创建管道),请发布单独的问题或搜索.

与其生成随机颜色,不如根据表格单元格中的值为每个单元格生成颜色.这样,您可以使用管道根据特定输入获取颜色代码:

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:

  1. 您可以执行以下操作,而不是 [ngStyle] ="getRandomColor()" : [style.background] ="cellValue | getRandomColor" .

在这里, 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.

  1. 创建管道.可以在此处采用管道的逻辑.
  1. 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.

这篇关于如何在html表中为每个记录显示一种随机的背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆