在兄弟組件之間傳遞數據 (Passing Data between sibling components)


問題描述

在兄弟組件之間傳遞數據 (Passing Data between sibling components)

我正在嘗試在兩個同級組件之間傳遞數據,組件結構如下所示。我需要在兩個兄弟組件之間傳遞數據,

我不想讓組件成為父子組件,而是我需要在兄弟組件之間傳遞數據

但是當按鈕點擊我得到錯誤:

TypeError: Cannot read property 'settDate' of undefined

不確定我們是否在這裡遺漏了什麼


參考解法

方法 1:

Since your components are under same parent, I assume PRJ Shipping Component is a SMART component and the rest are DUMB components (they only interact with Input and Output)

So you need to add an Output to reportingFilterComponent and emitting the filter value, then PRJ Shipping Component has event handler to get the value, and pass it as Input to tjl shipment component something like below

reportingFilterComponent.ts

@Output() filterChange : EventEmitter<ShipDateFilterModel[]> = new EventEmitter<ShipDateFilterModel[]>()

filterButtonClick() {
  this.filterChange.emit(/. your filter value../);
} 

PRJ Shipping Component.html

<app‑reporting (filterChange)="onFilterChange($event)"></app‑reporting>

<app‑tjl‑shipment [filter]="filter"></app‑tjl‑shipment>

PRJ Shipping Component.ts

filter: ShipDateFilterModel[];

onFilterChange(event:ShipDateFilterModel[]) {
   this.filter = event;
}

tjl‑shipment.component.ts

@Input() filter: ShipDateFilterModel[];

ngOnChanges(changes: SimpleChanges) {

  if (changes.filter && changes.filter.currentValue) {
     // do whatever is needed
  }
}

Improvement

For keeping the DUMB component DUMB, they shouldn't do any http call or something. so being said it better to PRJ Shipping Component receives the filter value and do the filter operation and just passing filtered data to tjl‑shipment.component

Another solution

You can create a service to keep the data between components and informing the changes, but in your case it's a needless complexity

(by trxReza)

參考文件

  1. Passing Data between sibling components (CC BY‑SA 2.5/3.0/4.0)

#angular7 #javascript #TypeScript #Angular






相關問題

更改角度 7 中打印值的顏色 (Change the colour of printed value in angular 7)

在Angular7中更改路線的頁面重新加載問題 (Page reload issue on changing the route in Angular7)

如何使用訂閱來映射對象 (How to map object using subscribe in angular)

Angular 文件夾結構 (Angular Folder Structure)

在兄弟組件之間傳遞數據 (Passing Data between sibling components)

如何在 *ngFor 中循環選擇標籤並獲取所選值 (how to loop throught select tags inside *ngFor and get the selected value)

如何測試角度事件監聽器? (How to test angular event listeners?)

Angular 7/8 響應開發服務器上的健康檢查 (Angular 7/8 respond to health-checks on the dev server)

NgRx Store:如何在兩個功能模塊之間共享數據 (NgRx Store : How to share the data between two feature modules)

根據角度表單構建器/組中其他字段的值運行並設置一個字段的驗證錯誤 (Run and set the validation errors on one field based on the value of other field in angular form builder/group)

如何更改 Angular Material 中的標籤標籤? (How to change tab label in Angular Material?)

429 Too Many Requests - Angular 7 - 多個文件上傳 (429 Too Many Requests - Angular 7 - on multiple file upload)







留言討論