我有两个组件“ YearComponent”和“ StatPeriod”组件。在我的YearComponent中,我这样调用StatPeriod:<app-save-stat-period [dateBegin]="dateBegin" [dateEnd]="dateEnd" byMonth bestNAverage></app-save-stat-period>
我有一个选择输入来选择年份:<mat-select [(value)]="yearSelected" (selectionChange)="dateChange()" placeholder="Année">
yearSelected变量通过这种方式管理
get dateBegin() {
return moment()
.year(this.yearSelected)
.startOf('year')
.format('YYYY-MM-DD');
}
get dateEnd() {
return moment()
.year(this.yearSelected)
.endOf('year')
.add(1, 'days')
.format('YYYY-MM-DD');
}
使用上面的代码,您可以看到当我的双向绑定yearSelected更改时,dateBegin()和dateEnd()会更新。
他是我使用的函数dateChange():
dateChange(): void {
this.statPeriod.reloadAverageBest(this.dateBegin, this.dateEnd);
}
this.statPeriod是使用此ViewChild创建的:@ViewChild(StatPeriodComponent, { static: false }) statPeriod: StatPeriodComponent;
下面描述方法reloadAverageBest():
reloadAverageBest(dateBegin: string, dateEnd: string) {
this.getStat(dateBegin, dateEnd);
this.getCalls();
this.getSaves();
}
我不明白的是,当我更改年份时,例如从2020年选择到2019年,我打电话给我的2020年而不是2019年的api。当我将其更改为2018时,它将调用2019;然后当我将其更改为2019或2020时,它将调用2018。
所以看来StatPeriodComponent是用之前选择的年份而不是我实际选择的年份刷新的。
您知道这里发生了什么吗?
问候
有时需要花费时间来反映两种方式的绑定。表示selectionChange
回调发生在两种方式的出价更新之前。
您可以尝试以下选项吗?
Change your select input
<mat-select [(value)]="yearSelected" (selectionChange)="dateChange($event)" placeholder="Année">
更改dateChange
函数以接受参数
dateChange({value}): void {
//here value will point to latest year
<<use value to convert dateBegin and dateEnd>>
}
第二选项
您为什么直接调用子函数?您正在将dateBegin
和dateEnd
传递给子组件,可以使用onChange
生命周期事件并调用API。