I have here this function in my service.ts
public getUploadPeriod(){
let baseYear = 2020;
let currYear = new Date().getFullYear();
let years = [];
for (var i = baseYear; i <= currYear; i ) {
years.push(i);
}
return years
}
And this is the ts of my project I am trying to call out the function that I create in service.ts
getUploadPeriod() {
const years = this.uploadFacilityService.getUploadPeriod();
console.log(years)
return years
}
And this is my html
<mat-select
placeholder="Select Time Period">
<mat-option value="">
{{ years }}
</mat-option>
</mat-select>
The years are already generated with the function that I created but theres no display in my dropdown list. Can someone help me with this. Thank you!
CodePudding user response:
As seen in the documentation for the Angular select:
To add options to the select, add
<mat-option>
elements to the<mat-select>
. Each<mat-option>
has a value property that can be used to set the value that will be selected if the user chooses this option. The content of the<mat-option>
is what will be shown to the user.
Remember that inside a select, the options must be generated iteratively if you want to fetch them from a collection. Thus, in your useCase, it would look like this:
<mat-label>Select time period</mat-label>
<mat-select [(ngModel)]="year" name="year">
<mat-option *ngFor="let year of years" [value]="year">
{{year}}
</mat-option>
</mat-select>
Read more about select and <mat-select>
: https://material.angular.io/components/select/overview
Edit: After taking a look at the rest of your code, years
should have a higher scope than the one you are giving it. So, initialize the variable in the component constructor and set its value inside of your method (remember to set this.years
). This way, the variable will be accessible from the component's template.
CodePudding user response:
{{ years }}
variable should be declared outside of method scope so template would have access to it.
years: any;
getUploadPeriod() {
this.years = this.serviceGetUploadPeriod();
console.log(this.years);
}
Use *ngFor
to iterate over items in template.
<div *ngFor="let year of years">
{{ year }}
</div>
Working example: https://stackblitz.com/edit/angular-ivy-4qd3ao?file=src/app/app.component.ts