【Angular】Angula6中的元件通訊
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