猿问

Angular - 检查后表达式已更改

好吧,我知道关于这个确切的问题有很多问题,但即使在阅读了其中一些之后,我也无法解决我的问题。我尝试了 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);

}

几天以来我一直在解决这个问题,无法弄清楚如何解决。如果有人可以向我解释,我缺少什么以及我的解决方案观点是什么,我会很高兴。


拉莫斯之舞
浏览 148回答 1
1回答

慕姐8265434

您可以尝试使用 DoCheck:class MyComponent implements OnInit, DoCheck {&nbsp; private _balance: number = 0;&nbsp; public balance: number;&nbsp; ngOnInit(): void {&nbsp; }&nbsp; ngDoCheck(): void {&nbsp; &nbsp; this.balance = this._balance;&nbsp; }&nbsp; updateBalance(balanceChange: number) {&nbsp; &nbsp; this._balance += balanceChange;&nbsp; }}但这似乎不是一个很好的解决方案。根据任务,您可以使用将存储总余额的服务,而无需将其添加到输入/输出中。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答