我有很多这样的年份链接:
<div class="header-years-container default-color">
<a class="years-items" *ngFor="let year of yearsLink;" [ngClass]="{'active': selectedYear === year}" (click)="onSelectYear($event.target.innerText)">
{{ year }}
</a>
</div>
和一个显示所选年份数据的属性。在ngOnInit方法中,我从数组设置了默认值,但是当用户单击该值时,我想传递year的其他值。在Typescript中看起来如下:
ngOnInit() {
this.yearsLink = [...new Set(this.absenceWidgetService.getAbsencesData().map(item => item.year))];
this.selectedYear = this.yearsLink[0];
this.selectedYear = this.onSelectYear(this.selectedYear);
this.absences = this.absenceWidgetService.getAbsencesData(this.selectedYear)
}
onSelectYear(value): string {
return this.selectedYear = value;
}
当用户单击事件时,如何每次在getAbsenceData方法中为selectedYear传递正确的值?目前,我一直都有默认值。
谢谢。
答案 0 :(得分:1)
您是否尝试过这种方法?
HTML:
<div class="header-years-container default-color">
<a class="years-items" *ngFor="let year of yearsLink;" [ngClass]="{'active': selectedYear === year}" (click)="onSelectYear(year)">
{{ year }}
</a>
</div>
TS:
onSelectYear(year) {
this.selectedYear = year;
}
答案 1 :(得分:0)
您无需使用$event
,您可以直接将year
用作函数中的参数
<div class="header-years-container default-color">
<a class="years-items" *ngFor="let year of yearsLink;" [ngClass]="{'active': selectedYear === year}"
(click)="onSelectYear(year)">{{ year }}</a>
</div>
答案 2 :(得分:0)
当我移动数据源属性填充事件方法时,我已经解决了问题。 ngOnInit()中为此属性提供了默认值,并为每个click事件传递了一个新值。
它看起来像这样:
ngOnInit() {
this.yearsLink = [...new Set(this.absenceWidgetService.getAbsencesData().map(item => item.year))];
this.selectedYear = this.yearsLink[0];
this.absences = this.absenceWidgetService.getAbsencesData(this.selectedYear)
}
onSelectYear(year) {
this.selectedYear = year;
this.absences = this.absenceWidgetService.getAbsencesData(this.selectedYear);
}