簡體   English   中英

從JSON數據填充的下拉列表

[英]Dropdown populated from json data

我希望我的下拉菜單顯示我的數據中的2017年和2018年。 2017和2018在我的json數據文件中重復很多次。 但是我希望在選擇時顯示所有2017年數據,並在選擇時顯示所有2018年數據。 當前,它顯示所有數據,並且下拉列表中的填充過多。

這是下拉菜單的HTML代碼:

<div class="row justify-content-center">
        <div class="col-4s">
        <p>Financial Year:</p>
        </div>
        <div class="col-4s">
            <select>
                <option *ngFor="let volumes of volumes">{{ volumes.month | 
                 date: 'yyyy' }}</option>
            </select>
        </div>
    </div>

Angular4代碼:導出類VehicleVolumeEditComponent實現OnInit {

volumes: Volumes[];
groupedVolumes : any;

constructor(private volumeService: VolumeService, private router: Router) { 
    this.volumeService.getVolumes().subscribe(volumes => {
        this.volumes = volumes;
        this.groupedVolumes = this.group(this.volumes);
        this.dataOk = true;
    }
}

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"
}
{
    "id": 10,
    "month": "2017-12-01"
}
{
    "id": 11,
    "month": "2018-01-01"
}
{
    "id": 12,
    "month": "2018-02-01"
}
{
    "id": 13,
    "month": "2018-03-01"
}
]

我會像這樣過濾掉數組中的唯一值-

this.unique_volumes = this.volumes.slice().map(value => value.month = new Date(value.month).getFullYear()).filter((years, index, array) => array.indexOf(years) === index);

然后在HTML,我會遍歷所有的unique_volumes而不是volumes

<option *ngFor="let volumes of unique_volumes">{{ volumes }}</option>

嘗試這個

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM