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

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. office 2016 官方原版 (含Visio Project 等全套 )下载地址 (不含破解,非网盘下载)不用登录

    原文地址:https://www.heidoc.net/joomla/technology-science/microsoft/8-office-2016-direct-download-links ...

  2. CustomScrollView

    body: CustomScrollView( slivers: [ SliverList( delegate: SliverChildBuilderDelegate( (context, int i ...

  3. Spark大型电商项目实战-及其改良(2) RDD优化效果不稳定的真正原因

    首先看没有map join的第2任务: 时间线如下 接着是对应id的算子计算时间表 Stage Id Description Submitted Duration Tasks: Succeeded/T ...

  4. Gatling实战(二)

    在上一篇实战讲解了Gatling的用例,不过还没涉及到性能方面的内容,其实用例中的最后一句就和性能有关了 setUp(scn.inject(atOnceUsers(1)).protocols(http ...

  5. [pycocotools修改]cocoeval.py

    __author__ = 'tsungyi' import numpy as np import datetime import time from collections import defaul ...

  6. linux编译链接找不到库文件的解决方法。

    今天编译出现ld: 0706-006 Cannot find or open library file: -l xerces-c_static,ld:open(): A file or directo ...

  7. 兼容ie8的前端下载方法

    背景:在xp系统上 ie8浏览器的下载需求,后端返回资源路径. 方法:谷歌下采用aDown下载,ie采用window.open 触发下载,如果不能自动自动下载,采用execCommand(" ...

  8. 关于在html中直接引入less文件遇到的小问题

    由于想直接在html页面上调用less文件,所以直接在代码上直接引入 <script src="bower_components/less/dist/less.js"> ...

  9. 使用Selenium模块报错的解决办法 (FileNotFound,WebDriverException)

    添加Chrome浏览器程序的目录到系统Path变量中: C:\Users\%USERNAME%\AppData\Local\Google\Chrome\Application ,使用pip3 inst ...

  10. Ubuntu16.04 使用sudo cat EOF 编辑文件,提示Permission denied错误的解决办法

    一.执行命令报错 在Ubuntu16.04下,使用如下命令,修改hosts主机文件,居然提示权限错误: catty@node186:~$ sudo cat <<EOF > /etc/ ...