父子組件數據傳遞
- 父級向子級傳遞對象: @Input
例如:一個下拉框的列表數據 options 來自父組件。
子組件代碼:
- 子組件向父組件觸發事件 @Output, EventEmitter
子組件代碼:
父組件代碼:
子組件中使用 @output + EventEmitter 定義一個可以對外的帶參事件,並在子組件內部的適當時機去觸發這個事件 this.search.emit(val),
父組件在使用子組件時,可以將子組件中定義的事件綁定到自己的內部函數。
子組件通過 @output 定義的event, 使用上等同於html 基本元素的 click 事件,都可以通過 (eventname)的形式進行事件綁定。
同級組件數據傳遞
沒有包含關系的兩個組件,如果想進行數據傳遞,根據業務要求的不同,可以自行選擇子父父子參數續傳,或者是通過 service。
這里介紹通過 service 實現兩個組件間的事件觸發及參數傳遞:
創建一個 service 專門用作各種情況下的 service 數據傳遞
////selected report
private selectedReportSource = new Subject<any>();
SelectedReport$ = this.selectedReportSource.asObservable();
SelecteReport(index: any) {
this.selectedReportSource.next(index);
}
selectedReportSource 用來保存選中的 report 唯一標志,SelectedReport$ 是一個選中 report 唯一標志的可訂閱對象, SelecteReport()方法用來修改選中的 report
在觸發改變的組件內,調用數據改變方法
import { AllService } from "../../../services/all.service";
this.all.share.SelecteReport(tabIndex);
import 定義數據服務的對象,通過服務方法改變選中的 report
在接收數據改變的組件內,監聽 subject 對象
import { Component, OnInit, OnDestroy } from '@angular/core';
import { AllService } from "../../../services/all.service";
import { Subscription } from 'rxjs';
export class ReportsComponent implements OnInit, OnDestroy {
subscription_selectReport: Subscription;
ngOnInit() {
this.subscription_selectReport = this.all.share.SelectedReport$.subscribe((x: number) => {
this.ActiveTab = x;
});
}
ngOnDestroy() {
this.subscription_selectReport.unsubscribe();
}
}
第一,引入數據服務 AllService
第二,添加組件的 OnDestroy, Subscription 引用
第三,定義一個 Subscription 對象,並注冊監聽 SelectedReport$.subscribe(),
第四,在 ngOnDestroy 中注銷監聽(避免內存泄漏)
注意:
如果不需要不同組件間事件的觸發,就不需要注冊監聽,直接在數據服務中提供一個數據訪問方法,由數據消費組件調用即可