一、父組件給子組件傳值 – @input
父組件不僅可以給子組件傳遞簡單的數據,還可把自己的方法以及整個父組件傳給子組件
1. 父組件調用子組件的時候傳入數據
<app-header [msg]="msg"></app-header>
2. 子組件引入 Input 模塊
import { Component, OnInit ,Input } from '@angular/core';
3. 子組件中 @Input 接收父組件傳過來的數據
export class HeaderComponent implements OnInit {
@Input() msg:string
constructor() { }
ngOnInit() {
}
}
4. 子組件中使用父組件的數據
<h2>這是頭部組件--{{msg}}</h2>
二、子組件通過@Output 觸發父組件的方法
1. 子組件引入 Output 和 EventEmitter
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
2.子組件中實例化 EventEmitter
@Output() private outer=new EventEmitter<string>();
/*用 EventEmitter 和 output 裝飾器配合使用 <string>指定類型變量*/
3. 子組件通過 EventEmitter 對象 outer 實例廣播數據
sendParent(){
this.outer.emit('msg from child')
}
4.父組件調用子組件的時候,定義接收事件 , outer 就是子組件的 EventEmitter 對象 outer
<app-header (outer)="runParent($event)"></app-header>
5.父組件接收到數據會調用自己的 runParent 方法,這個時候就能拿到子組件的數據
//接收子組件傳遞過來的數據
runParent(msg:string){
alert(msg);
}
三、父組件通過@ViewChild 主動獲取子組件的數據和方法
1.調用子組件給子組件定義一個名稱
<app-footer #footerChild></app-footer>
2. 引入 ViewChild
import { Component, OnInit ,ViewChild} from '@angular/core';
3. ViewChild 和剛纔的子組件關聯起來
@ViewChild('footerChild') footer;
4.調用子組件
run(){
this.footer.footerRun();
}
四、非父子組件通訊
1、公共的服務
2、Localstorage (推薦)
3、Cookie