【问题标题】:Changing colour of specific data更改特定数据的颜色
【发布时间】:2018-12-31 01:35:34
【问题描述】:

我想更改 json 文件中某些数据的颜色。 如果我有一个包含日期的数据集,并且我希望 2017 年的日期为浅粉色。我怎样才能在不影响 2018 年、2019 年等的情况下实现这一目标。日期。

Json 文件:

[
    {
        "id": 1,
        "month": "2017-03-01"
    }
    {
        "id": 2,
        "month": "2017-04-01"
    }
    {
        "id": 3,
        "month": "2017-05-01"
    }
    {
        "id": 4,
        "month": "2017-06-01"
    }
    {
        "id": 5,
        "month": "2017-07-01"
    }
    {
        "id": 6,
        "month": "2017-08-01"
    }
    {
        "id": 7,
        "month": "2017-09-01"
    }
    {
        "id": 8,
        "month": "2017-10-01"
    }
    {
        "id": 9,
        "month": "2017-11-01"
    }
    {
        "id": 10,
        "month": "2017-12-01"
    }
    {
        "id": 11,
        "month": "2018-01-01"
    }
    {
        "id": 12,
        "month": "2018-02-01"
    }
    {
        "id": 13,
        "month": "2018-03-01"
    }
]

这是我需要编辑的 HTML。我需要它,以便 2017 年的月份显示为浅粉色。 HTML:

<table>
  <tr>
    <th>Line 1</th>
    <th *ngFor="let volumes of volumes">{{ volumes.month | uppercase }}</th>
  </tr>
</table>

【问题讨论】:

  • 你应该完成你的 Angular 教程https://angular.io/tutorial,因为你所问的都写在那里了。
  • 这是正确的,除了我怎么能用日期来做到这一点。因为我希望它发生在 2017 年的所有日期。@SuhelKhan
  • 您可以使用 Date 构造函数从字符串中序列化 JS 日期,然后使用 .getYear() 方法获取日期的年份。从那里开始,它就像new Date(dateString).getYear() === '2017' ? 'pink': 'not-pink' 一样简单。听起来对指令来说是一项完美的工作。

标签: html css json angular


【解决方案1】:

将每个对象中的 Date 传递给组件,如下所示

import {
  Component
} from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  volumes: any[] = [{
      "id": 1,
      "month": "2017-03-01"
    },
    {
      "id": 2,
      "month": "2017-04-01"
    },
    {
      "id": 3,
      "month": "2017-05-01"
    },
    {
      "id": 4,
      "month": "2017-06-01"
    },
    {
      "id": 5,
      "month": "2017-07-01"
    },
    {
      "id": 6,
      "month": "2017-08-01"
    },
    {
      "id": 7,
      "month": "2017-09-01"
    },
    {
      "id": 8,
      "month": "2017-10-01"
    },
    {
      "id": 9,
      "month": "2017-11-01"
    },
    {
      "id": 10,
      "month": "2017-12-01"
    },
    {
      "id": 11,
      "month": "2018-01-01"
    },
    {
      "id": 12,
      "month": "2018-02-01"
    },
    {
      "id": 13,
      "month": "2018-03-01"
    }
  ];

  checkYear(date) {
    return new Date(date).getFullYear() == 2017 ? true : false;
  }
}
.pink-color {
  color: pink;
}
<table>
  <tr>
    <th>Line 1</th>
    <th *ngFor="let volume of volumes" [ngClass]="{ 'pink-color': checkYear(volume.month) }">
      {{ volume.id }}
    </th>
  </tr>
</table>

这里是Stackblitz

【讨论】:

  • 这很好用,谢谢。我只是有一个小问题。如果我想让 2018 年也有不同的颜色。我怎么能添加呢?
猜你喜欢
  • 2020-08-25
  • 2018-12-31
  • 1970-01-01
  • 1970-01-01
  • 2012-03-22
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 2013-07-10
相关资源
最近更新 更多