爲了演示【父子組件通訊】,我們首先通過CLI 創建兩個組件分別扮演父子組件(相對),分別是【parent】和 【child】:
//父子組件相對,這裏方便演示組件直接取名【parent】和【child】
ng generate component components/parent
ng generate component components/child
1.在組件【parent】中掛載子組件【child】,【parent.component.html】
<app-child></app-child>
查看子組件頁面是否運行,然後我們開始針對以下環節構建對應的代碼;
父組件給子組件通訊
- 子組件可以獲取父組件的數據;
- 子組件可以執行父組件的方法;
繼續上面的步驟,在父組件【parent】的【parent.component.ts】中構建一個字符串字段和一個方法,代碼如下:
//1.在class類中構建字段
public parentData:string = '我是parentData數據';
//2.在class類中構建方法
runParent():void{
console.log('我是Parent方法');
}
接下來我們再改造父組件【parent.component.html】頁面中掛載的子組件【app-child】:
<!-- 掛載組件 -->
<app-child [parentData]="parentData" [runParent]="runParent" [parent]="this"></app-child>
然後我們再把組件的【child.component.ts】文件中引入所需裝飾器【@Input】,改造代碼如下:
//1.引入裝飾器【Input】
import { Component, OnInit, Input } from '@angular/core';
//2.在class類中接收父組件中的字段和方法
@Input() parentData:any; //接收父組件傳的值
@Input() runParent:any; //接收父組件的方法
@Input() parent:any; //接收整個父組件
//3.在class類中創建子組件中的runChild方法
runChild():void{
console.log('我是child方法');
this.runParent();
}
最後我們在子組件【child.component.html】的頁面中添加如下代碼:
<h3>我是子組件</h3> <br/>
父傳子 =》 {{domData}} <br/>
<button (click)="runChild()">調用父組件parent的方法</button>
運行如下所示:
注:其中 【app-child】中的 [parent]="this" 相對比較特殊,子組件可以獲取整個父組件;
子組件給父組件通訊
- 父組件可以獲取子組件的數據;
- 父組件可以獲取子組件的方法;
父組件通過【@ViewChild】主動獲取子組件的數據和方法;
- 調用子組件給子組件定義一個名稱,自定義名稱【child】;
<!-- 掛載組件 -->
<app-child #child></app-child>
<!-- #aside,ng中使用ViewChild獲取dom -->
<aside #aside [ngClass]="{'aside': true}">
我是側邊欄
</aside>
- 子組件中定義字段和方法;
public childData:string = '獲取childData數據';
run():void{
console.log('我是子組件child的run()方法!');
}
- 父組件ts中引入【ViewChild】並獲取子組件的字段或方法;
//1.引入ViewChild 和 ElementRef
import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
//2.獲取子組件字段或方法
@ViewChild('child',{static:true}) child:any;
//ng推薦方式獲取dom元素,頁面【#aside】
@ViewChild('aside',{static:true}) aside:ElementRef;
//3.通過【ViewChild】獲取子組件裏面的方法和字段
getChildRun():void{
console.log(this.aside.nativeElement.innerText); //ViewChild獲取dom對象aside標籤的文本
this.child.run(); //調用子組件的方法
console.log(this.child.childData); //獲取子組件的字段
}
注:【ViewChild】可以獲取子組件的信息,同時還可以操作當前組件中的dom對象;
非父子組件通訊
- 組件之間傳值;
- 共享方法;
非父子組件通訊,通常使用服務【service】或者BOM對象(瀏覽器對象)【Local Storage】對象間接的實現。