好吧,我知道关于这个确切的问题有很多问题,但即使在阅读了其中一些之后,我也无法解决我的问题。我尝试了 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);
}
几天以来我一直在解决这个问题,无法弄清楚如何解决。如果有人可以向我解释,我缺少什么以及我的解决方案观点是什么,我会很高兴。
拉莫斯之舞
慕姐8265434
随时随地看视频慕课网APP
相关分类