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

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. jdk版本相关问题

    1.switch在jdk1.7版本之后开始支持String类型: 2.maven3版本默认支持jdk版本为jdk1.5 3.编辑器中jdk版本设置为1.7或1.8版本,但未指定maven中的jdk版本 ...

  2. Object.prototype的成员介绍

    3.Object.prototype的成员介绍        Object.prototype是js中所有的对象的祖宗        Object.prototype中所有的成员都可以被js中所有的对 ...

  3. kafka 控制台命令

    后台启动:bin/kafka-server-start.sh config/server.properties > /dev/null 2>&1 & 启动生产者:bin/k ...

  4. 腾讯这套SpringMvc面试题你了解多少?(面试必备)

    1.什么是 SpringMvc? 答:SpringMvc 是 spring 的一个模块,基于 MVC 的一个框架,无需中间整合层来整 2.Spring MVC 的优点: 答: 1)它是基于组件技术的. ...

  5. anaconda中安装mmdetection

    1.新建conda环境(有则跳过)     conda create -n py36 python=3.6 && source activate py36 2.安装pytorch    ...

  6. cv2.getRotationMatrix2D函数

  7. Android5.0新特性之——按钮点击效果动画(涟漪效果)

    Android5.0 Material Design设计的动画效果 RippleDrawable涟漪效果 涟漪效果是Android5.0以后的新特性.为了兼容性,建议新建drawable-v21文件夹 ...

  8. ace-editor线上代码编辑器

    package.json { "name": "vue-cli", "version": "1.0.0", " ...

  9. Linux 搭建DNS

    Linux 搭建DNS 使用yum源安装 yum -y install bind* 修改主配置文件 [root@localhost ~]# cp /etc/named.conf /etc/named. ...

  10. 关于transactionscope 事务的脏数据

    在一个项目中,关于新客的检测,如果查询到积分记录就是老客,因为检测的之前先积分,因为使用的是事务,造成本地代码没提交前已经有该会员的积分记录,而到数据库中却查询不到记录.造成永远都是老客,解决的方法是 ...