在我的角度项目中,我试图通过点击下一个/上一个按钮来浏览列表。我有一个复选框,可以将显示的小时数从几小时更改为几天。我希望能够在员工中来回走动,让价值观正确。我被告知可以通过ngOnChanges并跟踪上一个和新值来完成。
这就是我所拥有的,即更改新值,但我将如何更改之前的值?
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
for (let propName in changes) {
if (propName == "selectedEmployee") {
if (this.timeVar == "days") {
this.empInfo[this.selectedEmployee].STDLTD = this.empInfo[this.selectedEmployee].STDLTD * 8;
this.empInfo[this.selectedEmployee].Uncharged = this.empInfo[this.selectedEmployee].Uncharged * 8;
this.empInfo[this.selectedEmployee].PTOBase = this.empInfo[this.selectedEmployee].PTOBase * 8;
this.empInfo[this.selectedEmployee].PTOCarry = this.empInfo[this.selectedEmployee].PTOCarry * 8;
this.empInfo[this.selectedEmployee].PTOBorrowed = this.empInfo[this.selectedEmployee].PTOBorrowed * 8;
this.empInfo[this.selectedEmployee].PTOBalance = this.empInfo[this.selectedEmployee].PTOBalance * 8;
this.empInfo[this.selectedEmployee].PTORequests = this.empInfo[this.selectedEmployee].PTORequests * 8;
this.empInfo[this.selectedEmployee].PTORemaining = this.empInfo[this.selectedEmployee].PTORemaining * 8;
this.empInfo[this.selectedEmployee].ETOEarned = this.empInfo[this.selectedEmployee].ETOEarned * 8;
this.empInfo[this.selectedEmployee].ETORequests = this.empInfo[this.selectedEmployee].ETORequests * 8;
this.empInfo[this.selectedEmployee].ETORemaining = this.empInfo[this.selectedEmployee].ETORemaining * 8;
}
}
}
}
答案 0 :(得分:4)
ngOnChanges(changes: SimpleChanges) {
for (let propName in changes) {
let chng = changes[propName];
let cur = JSON.stringify(chng.currentValue);
let prev = JSON.stringify(chng.previousValue);
}
}
因此,您需要.currentValue
和.previousValue
属性才能访问当前和以前的值。
答案 1 :(得分:0)
使用ngOnChanges的更安全方式:
nameof.ts
export const nameof = <T>(name: keyof T) => name;
my.component.ts
selectedEmployee: string[];
ngOnChanges(changes: SimpleChanges): void {
// won't compile if 'selectedEmployee' is no a property of this component
const change = changes[nameof<MyComponent>('selectedEmployee')];
if (change) {
// casting it, to avoid dumb error that won't throw, like
// doing `change.currentValue > 0` instead of `change.currentValue.length > 0`
const previous: string[] = change.previousValue;
const current: string[] = change.currentValue;
// do something with it.
}
}