好吧,我知道关于这个确切的问题有很多问题,但即使在阅读了其中一些之后,我也无法解决我的问题。我尝试了 changeDetectionRef 的解决方案,但要么我做错了,要么它在我的情况下不起作用。对于我的问题:我正在制作一本预算书,添加交易和其他东西,一切都做得很好,直到我添加了一个余额概览,它显示了帐户的总体余额以及将在本月应用的更改。余额在 ngFor 指令中从父级(budget-book.component)发送到子级(day.component)。我明白了,我遇到的问题是,相同的值被发送给每个孩子,之后接收、更改并发送给下一个孩子。我尝试在父级中创建一个数组,其中保存每个 balanceChange 并发送前几天的总和,但这也没有成功。我也在考虑做一个可观察的。预算-book.component.html[...]<ul class="days"> <app-day (addEvent)="addTransaction($event)" (removeEvent)="removeTransaction($event)" (balanceEvent)="updateBalance($event)" *ngFor="let day of days; index as i" [date]="sendDate(this.date.getFullYear(), this.date.getMonth(), i + 1)" [transactions]="getTransactions(i)" [balance]="balance"></app-day></ul>[...]预算书.component.ts[...]balance: number;ngOnInit(): void { [...] this.balance = 0;}[...]updateBalance(balanceChange: number) { this.balance += balanceChange;}day.component.html<div class="header-balance-container"> <span [class.positive-number]="balance + balanceChange >= 0" [class.negative-number]="balance + balanceChange < 0" class="balance">{{balance + balanceChange | currency: 'EUR'}}</span> <span [class.positive-number]="balanceChange >= 0" [class.negative-number]="balanceChange < 0 " class="difference" >{{balanceChange | currency: 'EUR'}}</span></div>day.component.ts@Input() balance: number;balanceChange: number;@Output() balanceEvent = new EventEmitter<number>();ngOnChanges(): void { this.balanceChange = 0; if (this.transactions) { this.transactions.forEach((transaction: Transaction) => { this.balanceChange += transaction.value; }); } this.pushBalance(); // here is where i tried adding the changeDetectionRef}[...]pushBalance() { this.balanceEvent.emit(this.balanceChange);}几天以来我一直在解决这个问题,无法弄清楚如何解决。如果有人可以向我解释,我缺少什么以及我的解决方案观点是什么,我会很高兴。
1 回答
![?](http://img1.sycdn.imooc.com/5333a1d100010c2602000200-100-100.jpg)
慕姐8265434
TA贡献1813条经验 获得超2个赞
您可以尝试使用 DoCheck:
class MyComponent implements OnInit, DoCheck {
private _balance: number = 0;
public balance: number;
ngOnInit(): void {
}
ngDoCheck(): void {
this.balance = this._balance;
}
updateBalance(balanceChange: number) {
this._balance += balanceChange;
}
}
但这似乎不是一个很好的解决方案。根据任务,您可以使用将存储总余额的服务,而无需将其添加到输入/输出中。
添加回答
举报
0/150
提交
取消