本文主要介紹 Angular6 中的組件通訊
父組件綁定信息html
<app-child childTitle="可設置子組件標題"></app-child>
子組件接收消息cookie
import { Component, OnInit, Input } from '@angular/core'; @Input childTitle: string;
父組件觸發消息session
<app-child #child></app-child> <button (click)="child.childPrint()"></button>
子組件接收消息app
childPrint() { alert("來自子組件的打印"); }
子組件使用 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); }
子組件提供傳遞參數的函數this
sendInfo() { return 'Message from child 1.'; }
父組件使用 ViewChild 觸發並接收信息spa
<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(); }
缺點:須要雙向的觸發(發送信息 / 接收信息).net
service.tscode
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); } ...
優勢:真正的發佈訂閱模式,當數據改變時,訂閱者也能獲得響應
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; }); }
參考文獻