从JSON数据填充下拉列表

时间:2018-07-24 14:16:23

标签: json angular dropdown date-pipe

我希望我的下拉列表显示我的数据中的2017年和2018年。 2017和2018在我的json数据文件中重复很多次。但是我希望在选择时显示所有2017年数据,并在选择时显示所有2018年数据。当前,它显示所有数据,并且下拉列表中的填充过多。 有人告诉我尝试一下,但是没有设法使它起作用:

import {DatePipe} from '@angular/common';
.
.
volumes: Volumes[];
years: [] = [];
groupedVolumes : any;

constructor(private volumeService: VolumeService, private router: Router, private datePipe: DatePipe) { 

}


ngOnInit(){
    this.volumeService.getVolumes().subscribe(volumes => {
        this.volumes = volumes;
        for(let volume of volumes){
          if(this.years.indexOf(datePipe.formatDate(volume.month, 'yyyy')) === -1)
           this.years.push(datePipe.formatDate(volume.month, 'yyyy'));
        }
        this.groupedVolumes = this.group(this.volumes);
        this.dataOk = true;
    }

}

HTML:

<div class="row justify-content-center">
    <div class="col-4s">
    <p>Financial Year:</p>
    </div>
    <div class="col-4s">
        <select>
            <option *ngFor="let year of years">{{ year }}</option>
        </select>
    </div>
</div>

Json文件: 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"
}]

与此有关的问题是DatePipe。它仅具有转换功能,而没有formatDate。 也不喜欢年份:[] = []

1 个答案:

答案 0 :(得分:0)

ngOnInit() {
  this.years = this.volumeService.getVolumes().subscribe(volumes => {
    this.volumes = volumes;
    this.volumes.forEach(volume => {
      if(!this.years || !(this.years.some(year => year.includes(volume.month.split('-')[0])))) {
        this.years.push(volume.month.split('-')[0])
      }
  });
  this.groupedVolumes = this.group(this.volumes);
  this.dataOk = true;
}
相关问题