問題描述
在兄弟組件之間傳遞數據 (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