本文主要介绍 Angular6 中的组件通信
父组件绑定信息
<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("来自子组件的打印");
}
子组件使用 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);
}
子组件提供传递参数的函数
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.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);
}
...
优点:真正的发布订阅模式,当数据改变时,订阅者也能得到响应
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;
});
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有