Angula6_組件通信
本文主要介紹 Angular6 中的組件通信
一、父子組件通信
1.1 父組件向子組件傳遞信息
方法一 在父組件上設置子組件的屬性
父組件綁定信息
<app-child childTitle="可設置子組件標題"></app-child>
子組件接收消息
import { Component, OnInit, Input } from '@angular/core';
@Input childTitle: string;
方法二 父組件調用子組件的方法
父組件觸發消息
<app-child #child></app-child> <button (click)="child.childPrint()"></button>
子組件接收消息
childPrint() {
alert("來自子組件的打印");
}
1.2 子組件向父組件傳遞信息
方法一 使用 EventEmitter
子組件使用 EventEmitter 傳遞消息
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
...
@Output() initEmit = new EventEmitter<string>();
ngOnInit() {
this.initEmit.emit("子組件初始化成功");
}
...
父組件接收消息
<app-child (initEmit)="accept($event)"></app-child>
accept(msg:string) {
alert(msg);
}
方法二 使用 ViewChild
子組件提供傳遞參數的函數
sendInfo() {
return 'Message from child 1.';
}
父組件使用 ViewChild 觸發並接收信息
<button (click)="getInfo()">獲取子組件1號的信息</button>
<h2>{{ info }}</h2>
import { Component, OnInit, ViewChild } from '@angular/core';
...
@ViewChild(ChildFirstComponent) private childcomponent: ChildFirstComponent;
getInfo() {
this.info = this.childcomponent.sendInfo();
}
二、非父子組件通信
方法一 service
缺點:需要雙向的觸發(發送信息 / 接收信息)
service.ts
import { Component, Injectable, EventEmitter } from "@angular/core";
@Injectable()
export class myService {
public info: string = "";
constructor() {}
}
組件 1 向 service 傳遞信息
import { myService } from '../../service/myService.service';
...
constructor(
public service: myService
) { }
changeInfo() {
this.service.info = this.service.info + "1234";
}
...
組件 2 從 service 獲取信息
import { myService } from '../../service/myService.service';
...
constructor(
public service: myService
) { }
showInfo() {
alert(this.service.info);
}
...
方法二 使用 BehaviorSubject
優點:真正的發佈訂閱模式,當數據改變時,訂閱者也能得到響應
service
import { BehaviorSubject } from 'rxjs';
...
public messageSource = new BehaviorSubject<string>('Start');
changemessage(message: string): void {
this.messageSource.next(message);
}
組件調用 service 的方法傳信息和接收信息
changeInfo() {
this.communication.changemessage('Message from child 1.');
}
ngOnInit() {
this.communication.messageSource.subscribe(Message => {
window.alert(Message);
this.info = Message;
});
}
三、其他的通信方式
- 路由傳值
- cookie、session、storage
參考文獻