Angular父子組件通信

父傳子

1.使用@input方式傳值

	@Input('xxx') 可以接收一個參數用於父組件傳值時 [ ] 的名稱
	1. 在子組件的component.ts中導入Input並聲明該變量
	1.1 `import {Input} from '@angular/core`
	1.2 在構造函數中 @Input() xxx:any;  //any可以換成別的類型
	
	2. 在父組件中使用子組件時 如 <app-son [xxx]='fatherData'></app-son>  
		其中app-son是子組件 fatherData是父組件components中的變量 
		
	3. xxx使用和子組件中變量的使用沒什麼區別

2.使用inputs方式傳值

	1.在子組件component.ts中
	@component({
		inputs:['xxx']    //input是用來接收父組件傳遞的值
	})
	2.父組件使用子組件時 <app-son [xxx]='fatherData'></app-son>
		fatherData是父組件中的變量 不能直接寫字符串
	3. this.xxx即可正常使用

子傳父

1.使用ViewChild

	1. 給子組件添加標記
	<app-son #son></app-son>
	2. 導入ViewChild
	import { ViewChild } from '@angular/core';
	3. @ViewChild('son',{static:true}) son:any;
	4. 可以在html中直接使用 son.methodName 的方式調用子組件中的方法
	5. 需要注意的是 son只能在ngAfterViewInit()這個生命週期開始才能使用 只有當頁面初始化完成之後 纔可以拿到這個子組件

2.使用Output和EventEmitter

	1.導入Output和EventEmitter
	import { Output,EventEmitter } from ‘@angular/core’;
	2.在子組件類中創建事件 在生命週期函數中發送事件
	不要寫在contructor裏面 
	@Output() 接收一個參數 用於父組件調用時 ( ) 中的名稱
	@Output() sonEvent=new EventEmitter();
	ngOnInit(){
		this.sonEvent.emit('data');
   }
   3.當子組件事件觸發時 父組件使用方法接收 必須使用參數 $event接收數據
   <app-son (sonEvent)="getSonData($event)"></app-son >
   父組件的方法 
   getSonData(event:any){
		console.log(event);
   }

3.使用outputs

1.在子組件中
@Component({
		outputs:['sonEvent']
})
2.在類中定義子組件的事件
public sonEvent:EventEmitter<any>;
3. 在子組件的構造函數中初始化事件
this.sonEvent=new EventEmitter();
4.在需要發送的時候發送事件
this.sonEvent.emit('data');
5.當子組件事件觸發時 父組件使用方法接收 必須使用參數 $event接收數據
<app-son (sonEvent)="getSonData($event)"></app-son >
父組件的方法 
   getSonData(event:any){
		console.log(event);
   }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章