Reputation: 43
I am starting in Angular and would need to create a drop down list to select the year. Starting in 2020 until the current year, leaving the current year as the default. The data of the year will be collected later in the back to make a query and get the data of the chosen year and they are automatically displayed on the front when changing the year. I don't know how to start or if any angular packages need to be installed.
<select id="year" name="year" class="select_year cart_select italic light" />
<option selected hidden>Año</option>
<option value="2021">2021</option>
<option value="2020">2020</option>
</select>
This is how I have it now, but I need it to be dynamic and to update the year selected by default every year.
Upvotes: 3
Views: 6543
Reputation: 568
Here's a function that returns all years after the specified year
getCurrentYear() {
const date = new Date();
return date.getFullYear();
}
getYears(from) {
const years = [];
const currentYear = getCurrentYear();
for (let index = 0; index <= currentYear - from; index++) {
years.push(from + index);
}
return {years, currentYear};
}
<select id="year" name="year" [(ngModel)]="getCurrentYear()" class="select_year cart_select italic light" />
<option *ngFor="let year of getYears(2020).years" [ngValue]="year">{{ year }}</option>
</select>
put the above two methods in component.ts
file and invoke the getYears
function in the component.ts
file instead of HTML and assign it to variable
Upvotes: 1
Reputation: 26170
You could define an array of selectable years in your component as follows:
selectedYear: number;
years: number[] = [];
constructor() {
this.selectedYear = new Date().getFullYear();
for (let year = this.selectedYear; year >= 2020; year--) {
this.years.push(year);
}
}
Your template would have to look as follows:
<select ([ngModel])="selectedYear">
<option *ngFor="let year of years" [value]="year">{{ year }}</option>
</select>
Please take a look at this StackBlitz and see how it works.
Upvotes: 5