【问题标题】:Drop Down populated through Json通过 Json 填充的下拉列表
【发布时间】:2019-01-02 07:48:26
【问题描述】:

我希望下拉菜单显示我的数据中的 2017 年和 2018 年。 2017 年和 2018 年在我的 json 数据文件中重复了很多。但我希望在选择时显示所有 2017 年数据,并在选择时显示所有 2018 年数据。目前它显示所有数据,并且下拉列表被过度填充。有人告诉我试试这个,但没能成功:

filteredData: any[] = []
years: any[] = []

ngOnInit() {
  this.years = this.volumeService.getVolumes().subscribe(volumes => {
    this.volumes = volumes;
    this.volumes.forEach(volume => {
      // Assuming the volume month is formatted like your year months
      // If you prefer something cleaner with date reformatting. Look up moment.js and use it. 
      if(!(this.years.some(year => year.month.includes(volume.month.split('-')[0]))) {
        this.years.push(volume.month.split('-')[0])
      }
    });
  this.groupedVolumes = this.group(this.volumes);
  this.dataOk = true;
}

yearChange(newYear) {
  this.filteredData = this.years.filter(year => year.includes(newYear));
}

<select (change)="yearChange($event.target.value)">
    <option *ngFor="let year of filteredData">{{ year }}</option>
</select>

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"
}]

这个问题是分裂。拆分有一个错误,类型 Date 上不存在。

【问题讨论】:

  • 听起来编译器不知道month 属性是一个字符串。您是否为数组中的对象定义了类型?
  • 为什么要将订阅分配给this.years
  • 那是有人告诉我的,但这也造成了问题
  • 所以月份是一个日期属性。那么我应该将其转换为字符串以使用拆分功能吗?

标签: html json angular typescript dropdown


【解决方案1】:

您忘记将选项 value 设置为 id

<select (change)="yearChange($event.target.value)">
    <option *ngFor="let year of filteredData" [value]="year.id">{{ year.month }}</option>
</select>

stackblitz example

【讨论】:

  • 这有助于填充下拉列表,但不是我想要的方式。我需要对下拉列表进行分组。它需要按 2017 显示所有 2017 月份,按 2018 显示所有 2018 月份。它不希望在下拉列表中显示 2017 年的负载。
  • @L.C 我只是想确保我明白你的意思,这就是你想要的w3schools.com/tags/tryit.asp?filename=tryhtml_optgroup
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-10
  • 2013-04-16
  • 2021-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多