【发布时间】: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