实现组件交互有很多方式,下面列举。

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+ 实现组件交互的众多方式的更多相关文章

  1. React中组件间通信的方式

    React中组件间通信的方式 React中组件间通信包括父子组件.兄弟组件.隔代组件.非嵌套组件之间通信. Props props适用于父子组件的通信,props以单向数据流的形式可以很好的完成父子组 ...

  2. angular2 组件交互

    1. 组件通信 我们知道Angular2应用程序实际上是有很多父子组价组成的组件树,因此,了解组件之间如何通信,特别是父子组件之间,对编写Angular2应用程序具有十分重要的意义,通常来讲,组件之间 ...

  3. Angular2 父子组件通信方式

    https://www.jb51.net/article/133868.htm 这次给大家带来Angular2 父子组件通信方式,使用Angular2 父子组件通信方式的注意事项有哪些,下面就是实战案 ...

  4. vue组件间通信六种方式(完整版)

    本文总结了vue组件间通信的几种方式,如props. $emit/ $on.vuex. $parent / $children. $attrs/ $listeners和provide/inject,以 ...

  5. 轻量jquery框架之--组件交互基础设计

    概要 组件交互基础,即考虑在JQUERY对象下($)下扩展所有组件都需要用到的通用api,如ajax入口.对表单的操作.html片段加载.通用的配合datagrid通用的curd客户端对象等. 扩展a ...

  6. Vue加载组件、动态加载组件的几种方式

    https://cn.vuejs.org/v2/guide/components.html https://cn.vuejs.org/v2/guide/components-dynamic-async ...

  7. react学习笔记1之声明组件的两种方式

    //定义组件有两种方式,函数和类 function Welcome(props) { return <h1>Hello, {props.name}</h1>; } class ...

  8. vuejs组件交互 - 03 - vuex状态管理实现组件交互

    组件交互模式的使用场景 简单应用直接使用props down,event up的模式就可以了 小型应用使用事件中心模式即可 中大型应用使用vuex的状态管理模式 vuex 包含要管理的应用数据和更新数 ...

  9. React创建组件的三种方式比较

    推荐文章: https://www.cnblogs.com/wonyun/p/5930333.html 创建组件的方式主要有: 1.function 方式 2.class App extends Re ...

随机推荐

  1. c#检测是否存在数据库(SQL SERVER)

    private static bool CheckDatabaseExists( string databaseName) { { string sqlCreateDBQuery; bool resu ...

  2. IDEA 创建 web项目

    创建web步骤: 1.创建一个project File -> New Project -> 选择Java,Project SDK为1.7,勾选Web Application(创建web.x ...

  3. 升级python2.7, 实现python2.7与python3并存

    由于用到twilio模块, 所以需要升级一下python2, 但是又不想舍弃python2, 于是实现了简单的方法 python 先扔一块依赖 yum install zlib-devel bzip2 ...

  4. Unix系统的启动

    系统启动后: 第一个运行的进程是init 进程标识符为1. init派生一个getty.该进程负责打开终端端口,提供标准输入来源和标准输出.标准输出的去处,并且在屏幕上显示一个登录提示符 接下来执行/ ...

  5. kali网络配置

    touch 1.txt#创建一个文件 配置网卡 auto eth0iface eth0 inet staticaddress 172.16.30.102#要设置的主机IP地址netmask 255.2 ...

  6. Android ANR(应用无响应)解决分析【转】

    本文转载自:https://blog.csdn.net/u014630142/article/details/81709459 来自: http://blog.csdn.net/tjy1985/art ...

  7. Eclipse使用Maven,创建项目出现:Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resour

    使用maven创建简单的项目时候经常会遇到 Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resource ...

  8. VS Code插件配置

    常用 VS Code 插件: Auto Import 有了这个插件,就不需要再手动引入文件了.如果是基于组件的项目,直接输入组件名插件会自动处理 imported. ** Add jsdoc comm ...

  9. C语言: 简易图书管理系统

    这只是一个简易的图书管理系统,虽然它有千余行代码,不过终究是个简单基本的东西. 在Linux系统下,用Vim编写,如要在Windows上运行则需要一些改动,主要是一些调用系统函数的改动.如Window ...

  10. 51nod 1201 整数划分 dp

    1201 整数划分 基准时间限制:1 秒 空间限制:131072 KB   收藏  关注 将N分为若干个不同整数的和,有多少种不同的划分方式,例如:n = 6,{6} {1,5} {2,4} {1,2 ...