簡體   English   中英

Angular 如何將 2 個數據傳遞給子組件並使用 ngOnChanges 和 SimpleChanges

[英]Angular how to pass 2 datas to child component and use ngOnChanges and SimpleChanges

我正在嘗試將兩個變量發送到一個子組件並獲取每個變量的實時值,這僅適用於一個變量([Message] =“Message”),現在我需要傳遞另一個數據但我m 收到控制台錯誤:“找不到未定義的‘previousValue’”。 當我更新 totalAmountCart 變量(從 sessionStorage 獲取數據)時觸發此錯誤我該如何解決? 也許另一個生命循環鈎? 提前致謝

子組件(接收者):

 import { Component, OnInit, SimpleChanges, Input} from '@angular/core'; @Input() Message: string; @Input() totalAmountCart: number; ngOnChanges(changes: SimpleChanges) { const previousValue1 = changes.Message.previousValue; const currentValue1 = changes.Message.currentValue; if (previousValue1.== currentValue1) { this.userDetails = this;Message. } const previousValue2 = changes.totalAmountCart;previousValue. const currentValue2 = changes.totalAmountCart;currentValue. if (previousValue2.== currentValue2) { this;totalAmount = this.totalAmountCart; } }

父組件(發送者):

 @Component({ selector: 'app-store', template: '<app-header [Message]="Message" [totalAmountCart]="totalAmount"></app-header>', }) export class StoreComponent implements OnInit{ ngOnInit(){ getUserData(){ this.Message = '{ id: 1234, userName: Nick }' } } getSessionStorage(){ this.totalAmount = this.storageProducts.map(x => x.amount).reduce((a, b) => a + b); } }

如果我設置兩個 if 條件來評估更改它正在工作,無論如何我確信有更好的方法來解決這個問題

 ngOnChanges(changes: SimpleChanges) { if(changes.Message){ const previousValue1 = changes.Message.previousValue; const currentValue1 = changes.Message.currentValue; if (previousValue1.== currentValue1) { this.userDetails = this;Message. } } if(changes.totalAmountCart){ const previousValue2 = changes.totalAmountCart;previousValue. const currentValue2 = changes.totalAmountCart;currentValue. if (previousValue2.== currentValue2) { this;totalAmount = this.totalAmountCart; } } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM