1. 程式人生 > >angular組件間的信息傳遞

angular組件間的信息傳遞

TE war 引用 temp 事件 nco www www. bsp

原文

  https://www.jianshu.com/p/82207f2249c1

大綱

  1、父組件向子組件傳遞信息:通過屬性
  2、子組件向父組件傳遞信息:通過事件
  3、父組件獲取子組件的信息:通過調用模板引用變量
  4、父組件和子組件共享信息:通過服務共享信息
  5、父組件獲取子組件的信息:通過@ViewChild 或@ContentChild
  6、參考代碼

父組件向子組件傳遞信息:通過屬性

//父組件向子組件通過屬性傳遞信息
<app-childen [data]="parent_data"></app-childen>
//子組件通過@Input接受信息
@Input() data: string;

子組件向父組件傳遞信息:通過事件

//子組件傳遞信息給父組件
@Output() event = new EventEmitter();
private name: string;
upward() {
  /**
  * 實例化EventEmitter,賦值給event,event被@Output裝飾器定義為輸出屬性,
  * 這樣event具備了向上級傳遞數據的能力,通過調用EventEmitter類中定義的emit方法,
  * 來向上傳遞數據
  */
  this.event.emit(this.name);
}

//父組件通過事件接收子組件外傳的信息
<app-childen2 (event)="getData($event)"></app-childen2>

getData(event: any) {
  this.parent_name = event;
}

父組件獲取子組件的信息:通過調用模板引用變量

  通過@Input和@Output可以實現數據之間的傳遞,但是無法獲取子組件的類屬性和類方法,接下來我們通過局部變量方式實現獲取子組件其他成員。
  通過#號來標識一個變量, 這樣在父組件模板中創建了一個局部變量#chiden來獲取子組件的實例,調用子組件中的方法和屬性。

//在子組件中加上模板引用變量,方便父組件調用屬性方法
<app-childen3 #chiden></app-childen3>

//父組件通過子組件的模板引用變量來調用子組件的屬性和方法
<input type="button" 
    value="調用子組件方法" (click)="chiden.fun1()"
>
<input type="button" 
    value="調用子組件屬性" (click)="getChildInfo(chiden.childInfo)"
>

父組件和子組件共享信息:通過服務共享信息

  父子組件共享同一個服務,利用該服務實現雙向通信

父組件獲取子組件的信息:通過@ViewChild 或@ContentChild

  @ViewChild的作用是聲明對子組件元素的實例引用,意思是通過註入的方式將子組件註入到@ViewChild容器中,你可以想象成依賴註入的方式註入,只不過@ViewChild不能在構造器constructor中註入,因為@ViewChild會在ngAfterViewInit()回調函數之前執行。

import {Component, ViewChild} from ‘@angular/core‘;
import {ChildenComponent} from ‘./child.component‘;

@Component({
  selector: ‘app-parent‘,
  templateUrl: ‘./parent.component.html‘
})
export class ParentComponent {
  @ViewChild(ChildenComponent) child: ChildenComponent;

  OnClick() {
    this.child.fun1();
  }
}

參考代碼

  angular實例代碼中的angular-transfer-info中有我以上描述的代碼實例,如果有需要可以從裏面下載或者運行,希望能對讀者有所幫助。

angular組件間的信息傳遞