angular 父子元件通訊

2022-08-15 09:00:18 字數 1720 閱讀 1153

1.   子元件呼叫父元件的方法和資料 -- input 裝飾器

1. fathercomponent.html中

tochildstr -- 父元件中定義的資料

fathermethod -- 父元件中的方法

fathercomponent -- 父元件本身, this指代父元件例項,通過 [fathercompoent] 將父元件例項傳遞給子元件

2. childcomponent.ts 中

通過 @input 裝飾器獲取父元件屬性,方法,父元件例項

exportclasslogincomponentimplementsoninit

ngoninit()

getfathercomponentmethod()

}2.   父元件調動子元件的方法和資料 -- viewchild裝飾器

1. fathercomponent.html中

通過#var 方式給子元件標記

#child>

2. fathercomponent.ts中

通過@viewchild()裝飾器獲取子元件例項

@viewchild('child', null) childcomponent:any

userchildmethod()

3. 通過事件觸發器,子元件給父元件傳參。即父元件獲取子元件資料

以上兩種方式都是主動獲取資料或者方法。這種方式通過 eventemitter 和 output 方式相當於,通過事件,子元件廣播資料給父元件,父元件被動接受引數。

1. childcomponent.ts

import from'@angular/core';

exportclasslogincomponentimplementsoninit

sendparent()

2. childcomponent.html

通過事件觸發器,子元件向父元件廣播資料

(click)="sendparent()">資料傳送給父元件

3. parentcomponent.html,

通過 (事件觸發器)= 「方法」 的方式監聽子元件發出父訊息。 (事件觸發器) 必須與子元件中定義的名稱一致

(outer)="onrecivechildmsg($event)">

4. parentcomponent.ts

通過方法獲取傳遞的引數 $event

onrecivechildmsg(e)

angular 父子元件通訊

父元件不僅可以給子元件傳遞簡單的資料,還可以把自己的方法以及整個父元件傳給子元件 子元件獲取父元件的 msg 資料 父元件呼叫子元件的時候傳入資料 msg msg 子元件引入 input 模組 import from angular core 子元件中 input 接收父元件傳過來的資料 expor...

Angular元件 父子元件通訊

angular元件間通訊 元件之間松耦合,元件之間知道的越少越好。元件4裡面點選按鈕,觸發元件5的初始化邏輯。傳統做法 在按鈕4的點選事件裡呼叫元件5的方法。緊密耦合。angular 在元件4根本不知道元件5存在的情況下實現。使用松耦合的方式在元件之間傳遞資料開發出高重用性的元件。使用輸入輸出屬性在...

angular6之父子元件通訊

父元件向子元件傳入資料 父元件訪問子元件的方法和資料 方法一 新增方法二 父元件ts 中呼叫子元件的方法和屬性。首先匯入模組viewchild。import from angular core 在父元件的類中將子元件作為viewchild注入到父元件中 viewchild additemcompon...