Html 下拉列表通过Json填充

Html 下拉列表通过Json填充,html,json,angular,typescript,dropdown,Html,Json,Angular,Typescript,Dropdown,我希望我的下拉列表显示我的数据中的2017年和2018年。2017年和2018年在我的json数据文件中重复了很多次。但我希望所有2017年数据在选中时显示,所有2018年数据在选中时显示。目前,它显示所有数据,下拉列表填充过多。我被告知要试试这个,但没能成功: filteredData: any[] = [] years: any[] = [] ngOnInit() { this.years = this.volumeService.getVolumes().subscribe(volu

我希望我的下拉列表显示我的数据中的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>

这个问题是分裂。Split有一个错误,类型日期不存在。

您忘记将选项
值设置为id

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

{{年.月}

听起来好像编译器不知道
month
属性是字符串。您是否为数组中的对象定义了类型?为什么要将订阅分配给
this.years
?这是有人告诉我要做的,但这导致了问题,所以month是日期属性。那么,我应该将其转换为字符串以使用拆分函数吗?这有助于填充下拉列表,但不是我想要的方式。我需要对下拉列表进行分组。它需要按2017显示所有2017个月,按2018显示所有2018个月。它不想在下拉列表中显示2017年的内容。@L.C.我只想确定我明白了你的意思,这是你想要的吗
<select (change)="yearChange($event.target.value)">
    <option *ngFor="let year of filteredData" [value]="year.id">{{ year.month }}</option>
</select>