Angular 8 組件間數據共享

父子組件數據傳遞

  • 父級向子級傳遞對象: @Input

例如:一個下拉框的列表數據 options 來自父組件。

 

子組件代碼:

import { Component, Input } from '@angular/core';
 
@Input() options: Array<string>;
 
在子組件中,可以自由使用 options 對象。
在 js 中通過 this.options 去訪問列表數據
在 html 中 直接用 options 去訪問
 
父組件中使用
子組件一般直接在父組件的 html 中通過元素的形式添加進來,如
<app-search [options]="StatusStr"> </app-search>
 
options 是在子組件添加的對外屬性,[options] 表示通過數據模型綁定到子組件的 options 屬性上。StatusStr 是父組件(js文件)中定義的一個數據對象。
這樣就實現了將父組件的數據傳遞給了子組件。
 
  •  子組件向父組件觸發事件 @Output, EventEmitter

子組件代碼:

import { Component, Output, EventEmitter } from '@angular/core';
@Output() search = new EventEmitter<string>();
 
onSearch(keycode, val) {
    if (keycode == 13) {
      this.search.emit(val);
    }    
  }

 

 父組件代碼:

HTML:
<app-search (search)="searchUsers($event)"></app-search>
 
JS:
 searchUsers(val: string) {
    this.searchKey = val;
    this.getUsers(val);
  }
 

子組件中使用 @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 中註銷監聽(避免內存泄漏)

 

注意:

如果不需要不同組件間事件的觸發,就不需要註冊監聽,直接在數據服務中提供一個數據訪問方法,由數據消費組件調用即可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章