我希望我的下拉列表显示我的数据中的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"
}]
与此有关的问题是拆分。日期类型上不存在拆分错误。
答案 0 :(得分:0)
您忘记将选项value
设置为id
<select (change)="yearChange($event.target.value)">
<option *ngFor="let year of filteredData" [value]="year.id">{{ year.month }}</option>
</select>