Angular2+ 实现组件交互的众多方式
实现组件交互有很多方式,下面列举。
1.父组件向子组件传递数据:(属性绑定)
父组件 [子属性名] = "父属性名"
<child-content [data]="parentData"></child-content>
子组件通过@Input() data 来获取
@Input() data: any // data可根据使用场景自定义
2.子组件向父组件传递数据:(事件绑定)
子组件使用EventEmitter创建自定义事件,并且通过@Output装饰器将它作为属性暴露出来
import { Component, Output, EventEmitter } from '@angular/core'; @Component({
selector: 'child-content',
template: `<button (click)="childShow()">这是子组件,广播数据给父组件)</button>`
})
export class Child1Component {
str: string = '这是子组件数据';
@Output() outShow: EventEmitter<any> = new EventEmitter;
constructor(){}
childShow2(){
this.str = '这是子组件数据';
this.outShow2.emit(this.str);
}
}
父组件 通过绑定子组件暴露出来的属性来监听事件从而获取子组件数据
import { Component, ViewChild , ElementRef} from '@angular/core';
import { ChildComponent } from '../child/child.component'; @Component({
template: `
<child1-content (outShow)="parentShow($event)"></child1-content>
`
})
export class ParentComponent {
parentShow(event) {
alert('你好,' + event);
}
}
3.父组件使用子组件方法:(@ViewChild)
父组件调用子组件的方法需要在组件视图渲染后才能正常运行,否则会报错;可以在生命周期函数AfterViewInit中或之后调用
import { Component, ViewChild , ElementRef} from '@angular/core';
import { ChildComponent } from '../child/child.component'; @Component({
template: `
<button (click)="childViewChild.show1('你好,ViewChild')">ViewChild(获取子组件实例)</button>
`
})
export class ParentComponent {
str: string = '';
@ViewChild(ChildComponent)
childViewChild: ChildComponent;
}
child.component.ts 子组件代码
import { Component, Output, EventEmitter } from '@angular/core'; @Component({
selector: 'child-content',
template: ``
})
export class ChildComponent {
str: string = '这是子组件数据';
constructor(){}
show1(event){
alert('父组件传来的值是:'+ event);
}
}
4.父组件使用子组件属性与事件:(# 局部变量)
parent..component.ts 父组件代码
import { Component, ViewChild , ElementRef} from '@angular/core';
import { ChildComponent } from '../child/child.component'; @Component({
template: `
<button (click)="child.show1('你好,局部变量!')">局部变量(获取子组件实例)</button>
<child-content #child></child-content>
selector: 'partvar-content'
})
export class ParentComponent { }
child.component.ts 子组件代码(同1.的子组件代码)
5.跨组件传递数据
通过服务Service和RXJS的观察者模式Subject进行通信。
message.service.ts 提供发送/接收的对外方法:
import { Injectable } from "@angular/core";
import { ReplaySubject, Observable } from "rxjs"; @Injectable()
export class MessageService {
// 这里之所以不用Subject,是想让新加入的观察者能接收到之前的一条广播
private valueUpdated: ReplaySubject<any> = new ReplaySubject<any>(1);
constructor() { }
sendMessage(val:String) {
this.valueUpdated.next(val);
}
clearMessage(){
this.valueUpdated.next();
}
getMessage(): Observable<any> {
return this.valueUpdated.asObservable();
}
}
使用的地方需要注册message服务
constructor(private message: MessageService) { }
ngAfterViewInit(): void {
this.subscription = this.message.getMessage().subscribe(msg => {
// 根据msg,来处理你的业务逻辑。
})
} // 组件生命周期结束的时候,记得注销一下,不然会卡卡卡卡;
ngOnDestroy(): void {
this.subscription.unsubscribe();
} // 调用该服务的方法,发送信息;
send():void {
this.message.sendMessage(2); // 发送信息消息
}
总结:这里的MessageService,就相当于使用广播机制,在所有的组件之间传递信息;不管是数字,字符串,还是对象都是可以传递的,而且这里的传播速度也是很快的
Angular2+ 实现组件交互的众多方式的更多相关文章
- React中组件间通信的方式
React中组件间通信的方式 React中组件间通信包括父子组件.兄弟组件.隔代组件.非嵌套组件之间通信. Props props适用于父子组件的通信,props以单向数据流的形式可以很好的完成父子组 ...
- angular2 组件交互
1. 组件通信 我们知道Angular2应用程序实际上是有很多父子组价组成的组件树,因此,了解组件之间如何通信,特别是父子组件之间,对编写Angular2应用程序具有十分重要的意义,通常来讲,组件之间 ...
- Angular2 父子组件通信方式
https://www.jb51.net/article/133868.htm 这次给大家带来Angular2 父子组件通信方式,使用Angular2 父子组件通信方式的注意事项有哪些,下面就是实战案 ...
- vue组件间通信六种方式(完整版)
本文总结了vue组件间通信的几种方式,如props. $emit/ $on.vuex. $parent / $children. $attrs/ $listeners和provide/inject,以 ...
- 轻量jquery框架之--组件交互基础设计
概要 组件交互基础,即考虑在JQUERY对象下($)下扩展所有组件都需要用到的通用api,如ajax入口.对表单的操作.html片段加载.通用的配合datagrid通用的curd客户端对象等. 扩展a ...
- Vue加载组件、动态加载组件的几种方式
https://cn.vuejs.org/v2/guide/components.html https://cn.vuejs.org/v2/guide/components-dynamic-async ...
- react学习笔记1之声明组件的两种方式
//定义组件有两种方式,函数和类 function Welcome(props) { return <h1>Hello, {props.name}</h1>; } class ...
- vuejs组件交互 - 03 - vuex状态管理实现组件交互
组件交互模式的使用场景 简单应用直接使用props down,event up的模式就可以了 小型应用使用事件中心模式即可 中大型应用使用vuex的状态管理模式 vuex 包含要管理的应用数据和更新数 ...
- React创建组件的三种方式比较
推荐文章: https://www.cnblogs.com/wonyun/p/5930333.html 创建组件的方式主要有: 1.function 方式 2.class App extends Re ...
随机推荐
- deepin Gtk-WARNING **: 无法在模块路径中找到主题引擎:“adwaita”
虽然没影响使用,但是看着有点不爽. 执行 sudo apt-get install gnome-themes-standard 就可以了.
- PHP CURL 账号密码 添加授权Authorization头Header
<?phpfunction http_request_xml($url,$data = null,$arr_header = null){ $curl = curl_init(); curl_s ...
- 010 Editor Mac安装教程
010 Editor mac版是mac上一款非常强大的十六进制编辑器,可以帮助用户进行编辑十六进制和二进制,可选择自己需要的进制进行编辑,还可对任何的文件进行编辑:软件内置了强大的模块.脚本操作,只需 ...
- Spring中三种编程式事务的使用
引入事务管理器 @Autowired TransactionTemplate transactionTemplate; @Autowired PlatformTransactionManager tr ...
- 解决 js ajax跨域访问报“No 'Access-Control-Allow-Origin' header is present on the requested resource.”错误
参考页面:https://blog.csdn.net/idomyway/article/details/79572973 如果请求的是PHP页面: header("Access-Contro ...
- ERROR: Got error reading packet from server: A slave with the same server_uuid/server_id as this slave has connected to the master
centos7.5 做binlog-server,拉取主库binlog报错 问题: [root@db03-53 binlog]# mysqlbinlog -R --host=10.0.0.55 --u ...
- 编码原则 之 Stable Dependencies
The Stable Dependencies Principle states that “The dependencies between software packages should be ...
- centOS 及 ubuntu 下载地址记录
CentOS下载地址: http://isoredirect.centos.org/centos/7/isos/x86_64/CentOS-7-x86_64-DVD-1611.iso : ubu ...
- JavaWeb网上商城项目中用户注册,使用MailServer和FoxMail搭建本地邮件服务器
下载并安装易邮邮件服务器MailServer和腾讯邮箱FoxMail,下载地址 https://download.csdn.net/download/checkerror2/10130538 具体步 ...
- git\CentOS6.5中gitlab安装教程
一.Git 起源: Git是一个开源的分布式版本控制系统,用于敏捷高效地处理任何或小或大的项目. Git 是 Linus Torvalds 为了帮助管理 Linux 内核开发而开发的一个开放源码的版本 ...