Angular 8 元件間資料共享

2022-08-23 16:21:12 字數 1988 閱讀 4826

父子元件資料傳遞

例如:乙個下拉框的列表資料 options 來自父元件。

子元件**:

import  from '@angular/core';

@input() options: array;

在子元件中,可以自由使用 options 物件。

在 js 中通過 this.options 去訪問列表資料

在 html 中 直接用 options 去訪問

父元件中使用

子元件一般直接在父元件的 html 中通過元素的形式新增進來,如

options 是在子元件新增的對外屬性,[options] 表示通過資料模型繫結到子元件的 options 屬性上。statusstr 是父元件(js檔案)中定義的乙個資料物件。

這樣就實現了將父元件的資料傳遞給了子元件。

子元件**:

import  from '@angular/core';

@output() search = new eventemitter();

onsearch(keycode, val)     

}父元件**:

html:

js:searchusers(val: string) 

子元件中使用 @output + eventemitter 定義乙個可以對外的帶參事件,並在子元件內部的適當時機去觸發這個事件 this.search.emit(val),

父元件在使用子元件時,可以將子元件中定義的事件繫結到自己的內部函式。

子元件通過 @output 定義的event, 使用上等同於html 基本元素的 click 事件,都可以通過 (eventname)的形式進行事件繫結。

同級元件資料傳遞

沒有包含關係的兩個元件,如果想進行資料傳遞,根據業務要求的不同,可以自行選擇子父父子引數續傳,或者是通過 service。

這裡介紹通過 service 實現兩個元件間的事件觸發及引數傳遞:

////selected report 

private selectedreportsource = new subject();

selectedreport$ = this.selectedreportsource.asobservable();

selectereport(index: any) 

selectedreportsource 用來儲存選中的 report 唯一標誌,selectedreport$ 是乙個選中 report 唯一標誌的可訂閱物件, selectereport()方法用來修改選中的 report 

import  from "../../../services/all.service";

this.all.share.selectereport(tabindex);

import 定義資料服務的物件,通過服務方法改變選中的 report

import  from '@angular/core';

import  from "../../../services/all.service";

import  from 'rxjs';

export class reportscomponent implements oninit, ondestroy );

}ngondestroy() 

}第一,引入資料服務 allservice 

第二,新增元件的 ondestroy, subscription  引用

第三,定義乙個 subscription 物件,並註冊監聽 selectedreport$.subscribe(),

第四,在 ngondestroy 中登出監聽(避免記憶體洩漏)

注意:如果不需要不同元件間事件的觸發,就不需要註冊監聽,直接在資料服務中提供乙個資料訪問方法,由資料消費元件呼叫即可

angular8 封裝元件

元件封裝的意義和方法 需要重用,或者簡化邏輯 ng generate component元件名 駝峰模式 使用index.ts方便匯入以及隔離內部變化對外部的影響 ng g c 元件名 駝峰模式 如果想在某個資料夾下新建元件 ng g c 檔名 元件名 駝峰模式 在每乙個資料夾下新建乙個index....

angular8的元件的生命週期

constructor 建構函式永遠首先被呼叫 ngonchanges 輸入屬性變化時被呼叫 在元件的 input 屬性發生變化的時候呼叫 ngoninit 元件初始化時被呼叫 ngdocheck 髒值檢測時呼叫 會呼叫多次 ngaftercontentinit 當內容投影ng content完成時...

Angular 7 學習資料 (2)元件

元件控制螢幕上被稱為檢視的一小片區域。當使用者在應用中穿行時,angular 就會建立 更新 銷毀一些元件。你的應用可以通過一些可選的生命週期鉤子 比如ngoninit 來在每個特定的時機採取行動。component裝飾器會指出緊隨其後的那個類是個元件類,並為其指定元資料。元件的元資料告訴 angu...