如何在<select>的顶部显示所选选项

时间:2019-12-24 06:52:40

标签: html angular

enter image description here

[1]: https://i.stack.imgur.com/9Fsvp.png

想要在年份的选择框中显示所选的年份,则意味着此处的1999年应为1980年。(单击上面的链接以查看图像) 不知道我该怎么做。

 <select [ngModel]="activeDate.getFullYear()" (ngModelChange)="changeYear($event);">
            <option *ngFor="let year of years; trackBy: trackBySelf" [value]="year">{{year}}</option>
          </select>

1 个答案:

答案 0 :(得分:0)

组件:

years = [2000,2001,2002];
// Selected option on page load.
selectedYear = this.years[0];

onChange(){
    // Get index of the selected item.
    var removeIndex = this.years.indexOf(this.selectedYear);
    // Remove the selected item.
    var removedItem= this.years.splice(removeIndex, 1)[0];
    // Sort the remaining array.
    this.years = this.years.sort();
    // Insert the removed item at the beginning.
    this.years.splice(0, 0, removedItem)
}

HTML:

<select [(ngModel)]="selectedYear" (change)="onChange()">
    <option *ngFor="let year of years" [ngValue]="year">{{year}}</option>
</select>