Angular4 组件通讯方法大全(推荐)

组件通讯,意在不同的指令和组件之间共享信息。如何在两个多个组件之间共享信息呢。

最近在项目上,组件跟组件之间可能是父子关系,兄弟关系,爷孙关系都有。。。。。我也找找了很多关于组件之间通讯的方法,不同的方法应用在不同的场景,根据功能需求选择组件之间最适合的通讯方式。下面我就总结一下关于组件通讯的N多种方法。

1.父→子 input

parent.ts

import { Component } from '@angular/core';

@Component({
 selector: 'page-parent',
 templateUrl: 'parent.html',
})
export class ParentPage {
 i: number = 0;
 constructor() {
  setInterval(() => {
   this.i++;
  }, 1000)
 }
}

parent.html

<ion-header>
 <ion-navbar>
  <ion-title>Parent</ion-title>
 </ion-navbar>
</ion-header>

<ion-content padding>
 <h2>Parent</h2>
 <page-child [content]="i"></page-child>
</ion-content>

child.ts

import { Component,Input } from '@angular/core';

@Component({
 selector: 'page-child',
 templateUrl: 'child.html',
})
export class ChildPage {
@Input() content:string;
 constructor() {
 }
}

child.html

<ion-content padding>
child:{{content}}
</ion-content>

结果:

2.子→父 output

parent.ts

import { Component } from '@angular/core';

@Component({
 selector: 'page-parent',
 templateUrl: 'parent.html',
})
export class ParentPage {
 i: number = 0;

 numberIChange(i:number){
   this.i = i;
 }
}

parent.html

<ion-header>
 <ion-navbar>
  <ion-title>Parent</ion-title>
 </ion-navbar>
</ion-header>

<ion-content padding>
 <h2>Parent:{{i}}</h2>
 <page-child (changeNumber)="numberIChange($event)"></page-child>
</ion-content>

child.ts

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
 selector: 'page-child',
 templateUrl: 'child.html',
})

export class ChildPage {
 @Output() changeNumber: EventEmitter<number> = new EventEmitter();
 Number: number = 0;
 constructor() {
  setInterval(() => {
   this.changeNumber.emit(++this.Number);
  }, 1000)
 }
}

child.html

<ion-content padding>
   child
</ion-content>

结果:

3.子获得父实例

parent.ts

import { Component } from '@angular/core';

@Component({
 selector: 'page-parent',
 templateUrl: 'parent.html',
})
export class ParentPage {
 i:number = 0;
}

parent.html

<ion-header>
 <ion-navbar>
  <ion-title>Parent</ion-title>
 </ion-navbar>
</ion-header>

<ion-content padding>
 <h1>parent: {{i}}</h1>
 <page-child></page-child>
</ion-content>

child.ts

import { Component, Input, EventEmitter, Output,Host,Inject,forwardRef } from '@angular/core';
import{ParentPage} from '../parent/parent';
@Component({
 selector: 'page-child',
 templateUrl: 'child.html',
})
export class ChildPage {
  constructor( @Host() @Inject(forwardRef(() => ParentPage)) app: ParentPage) {
    setInterval(() => {
      app.i++;
    }, 1000);
  }
}

child.html

<ion-content padding>
 child
</ion-content>

结果:

4.父获得子实例

parent.ts

import {ViewChild, Component } from '@angular/core';
import{ChildPage}from '../child/child';

@Component({
 selector: 'page-parent',
 templateUrl: 'parent.html',
})
export class ParentPage {
 @ViewChild(ChildPage) child:ChildPage;
  ngAfterViewInit() {
    setInterval(()=> {
      this.child.i++;
    }, 1000)
  }
}

parent.html

<ion-header>
 <ion-navbar>
  <ion-title>Parent</ion-title>
 </ion-navbar>
</ion-header>

<ion-content padding>
 <h1>parent {{i}}</h1>
 <page-child></page-child>
</ion-content>

child.ts

import { Component, Input, EventEmitter, Output,Host,Inject,forwardRef } from '@angular/core';

@Component({
 selector: 'page-child',
 templateUrl: 'child.html',
})
export class ChildPage {
  i:number = 0;
}

child.html

<ion-content padding>
<h2>child {{i}}</h2>
</ion-content>

结果:

5.service

parent.ts

import { Component } from '@angular/core';
import{myService}from '../child/myService'

@Component({
 selector: 'page-parent',
 templateUrl: 'parent.html',
})
export class ParentPage {

   i:number=0;

  constructor(service:myService) {
    setInterval(()=> {
      service.i++;
    }, 1000)
  }
}

parent.html

<ion-header>
 <ion-navbar>
  <ion-title>Parent</ion-title>
 </ion-navbar>
</ion-header>

<ion-content padding>
  <h1>parent {{i}}</h1>
  <page-child></page-child>
</ion-content>

child.ts

import { Component} from '@angular/core';
import{myService}from "../child/myService"
@Component({
 selector: 'page-child',
 templateUrl: 'child.html',
})
export class ChildPage {
  constructor(public service:myService){
  }
}

child.html

<ion-content padding>
<h2>child {{service.i}}</h2>
</ion-content>

myService.ts

ps:记得在app.module.ts 加上providers: [KmyService]

import{Injectable } from '@angular/core';
@Injectable()
export class KmyService {
  i:number = 0;
}

结果:

6.EventEmitter

myService.ts

import {Component,Injectable,EventEmitter} from '@angular/core';
@Injectable()
export class myService {
  change: EventEmitter<number>;

  constructor(){
    this.change = new EventEmitter();
  }
}

parent.ts

import { Component } from '@angular/core';
import{myService}from '../child/myService'

@Component({
 selector: 'page-parent',
 templateUrl: 'parent.html',
})
export class ParentPage {
  i:number = 0;
  constructor(service:myService) {
    setInterval(()=> {
      service.change.emit(++this.i);
    }, 1000)
  }
}

parent.html

<ion-header>
 <ion-navbar>
  <ion-title>Parent</ion-title>
 </ion-navbar>
</ion-header>

<ion-content padding>
  <h1>parent {{i}}</h1>
  <page-child></page-child>
</ion-content>

child.ts

import { Component, EventEmitter} from '@angular/core';

import{myService}from "../child/myService"
@Component({
 selector: 'page-child',
 templateUrl: 'child.html',
})
export class ChildPage {

  i:number = 0;

  constructor(public service:myService){
    service.change.subscribe((value:number)=>{
      this.i = value;
    })
  }

}

child.html

<ion-content padding>
 <h2>child {{i}}</h2>
</ion-content>

结果:

7.订阅

parent.ts

import { Component } from '@angular/core';
import{myService}from '../child/myService'

@Component({
 selector: 'page-parent',
 templateUrl: 'parent.html',
})
export class ParentPage {
  i:number=0;
  constructor(public service:myService) {
    setInterval(()=> {
       this.service.StatusMission(this.i++);
    }, 1000)
  }
}

parent.html

<ion-header>
 <ion-navbar>
  <ion-title>Parent</ion-title>
 </ion-navbar>
</ion-header>

<ion-content padding>
  <h1>parent</h1>
  <page-child></page-child>
</ion-content>

child.ts

import { Component, Injectable } from '@angular/core'
import { myService } from "../child/myService"
import { Subscription } from 'rxjs/Subscription';
@Component({
  selector: 'page-child',
  templateUrl: 'child.html',
})
export class ChildPage {
  i:number=0;
  subscription: Subscription;
  constructor(private Service: myService) {
    this.subscription = Service.Status$.subscribe(message => {
      this.i=message;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

child.html

<ion-content padding>
 <h2>child {{i}}</h2>
</ion-content>

myService.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class myService {

  private Source=new Subject<any>();
  Status$=this.Source.asObservable();
  StatusMission(message: any) {
    this.Source.next(message);
  }
}

结果:

以上七种组件与组件的通讯方式,可以选择应用于适合的场景里面,根据情况吧。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 详解Angular2组件之间如何通信

    组件之间的共享可以有好几种方式 父->子 input 方式 import {Component,Input} from 'angular2/core'; @Component({ selector: 'child', template: ` <h2>child {{content}}</h2> ` }) class Child { @Input() content:string; } @Component({ selector: 'App', directives: [Chi

  • angular4 共享服务在多个组件中数据通信的示例

    应用场景,不同组件中操作统一组数据,不论哪个组件对数据进行了操作,其他组件中立马看到效果.这样他们就要共用一个服务实例,是本次的重点,如果不同实例,那么操作的就不是同一组数据,那么就不会有这样的效果,想实现共用服务实例,就是在所有父组件中priviates:[]中引入这个组件,子组件中不需要再次引入,那么他们都是用的父组件中的服务实例. 1.公用服务 import {Injectable} from "@angular/core"; @Injectable() export class

  • Angular2 父子组件通信方式的示例

    Angular2官方文档对组件交互这块有详细的介绍-->文档--组件之间的交互.按文档介绍,组件间交互的方式一共有4种,包括: 通过输入型绑定把数据从父组件传到子组件(@Input decoration):子组件暴露一个EventEmitter属性(@Output decoration),当事件发生时,利用该属性emits向父组件发射事件. 父组件与子组件通过本地变量互动.(# var) 父组件调用@ViewChild. 父组件和子组件通过服务来通讯. 我在这里只总结.详细介绍3种我在项目中使用

  • Angular2 组件通信的实例代码

    1. 组件通信 我们知道Angular2应用程序实际上是有很多父子组价组成的组件树,因此,了解组件之间如何通信,特别是父子组件之间,对编写Angular2应用程序具有十分重要的意义,通常来讲,组件之间的交互方式主要有如下几种: 使用输入型绑定,把数据从父组件传到子组件 通过 setter 拦截输入属性值的变化 使用 ngOnChanges 拦截输入属性值的变化 父组件监听子组件的事件 父组件与子组件通过本地变量互动 父组件调用 ViewChild 父组件和子组件通过服务来通讯 本文会通过讲解着几

  • Angular2 父子组件数据通信实例

    如今的前端开发,都朝组件式开发模式靠拢,如果使用目前最流行的前端框架Angular和React开发应用,不可避免地需要开发组件,也就意味着我们需要考虑组件间的数据传递等问题,不过Angular 2已经为我们提供了很好的解决方案. 父组件和子组件 接触过面向对象编程的开发者肯定不会对父子关系陌生,在Angular 2中子组件存在于父组件"体内",并且父子组件可以通过一些渠道进行通讯. 父组件向子组件传入数据 – @Input 当我们着手开始开发一个组件时,第一件想到的应该就是为其传入数据

  • angular中不同的组件间传值与通信的方法

    本文主要介绍angular在不同的组件中如何进行传值,如何通讯.主要分为父子组件和非父子组件部分. 父子组件间参数与通讯方法 使用事件通信(EventEmitter,@Output): 场景:可以在父子组件之间进行通信,一般使用在子组件传递消息给父组件: 步骤: 子组件创建事件EventEmitter对象,使用@output公开出去: 父组件监听子组件@output出来的方法,然后处理事件. 代码: // child 组件 @Component({ selector: 'app-child',

  • Angularjs2不同组件间的通信实例代码

    AngualrJs2官方方法是以@Input,@Output来实现组件间的相互传值,而且组件之间必须父子关系,下面给大家提供一个简单的方法,实现组件间的传值,不仅仅是父子组件,跨模块的组件也可以实现传值 /** *1.定义一个服务,作为传递参数的媒介 */ @Injectable() export class PrepService{ //定义一个属性,作为组件之间的传递参数,也可以是一个对象或方法 profileInfo: any; } /** *2.传递参数的组件,我这边简单演示,直接就在构

  • Angular 2父子组件之间共享服务通信的实现

    前言 如今的前端开发,都朝组件式开发模式靠拢,如果使用目前最流行的前端框架Angular和React开发应用,不可避免地需要开发组件,也就意味着我们需要考虑组件间的数据传递等问题,不过Angular 2已经为我们提供了很好的解决方案. 本文详细介绍了Angular2父子组件共享服务通信的相关内容,父子组件共享同一个服务,利用该服务实现双向通信,下面来看看详细的介绍: 第一步:定义服务 parentService.ts 1).这里用Injectable修饰这个类是一个服务,在其他用到地方只需要注入

  • Angular2 组件间通过@Input @Output通讯示例

    本文介绍了Angular2 组件间通过@Input @Output通讯示例,分享给大家,具体如下: 父组件传给子组件: 子组件设置@Input属性,父组件即可通过设置html属性给子组件传值. 子组件: @Input() title:string; _name:string = ''; @Input() set name(name:string) { this._name=(name&&name.trim())||''; } 上面的代码设置了两个可供父组件传入的属性:title和name,

  • Angular4 组件通讯方法大全(推荐)

    组件通讯,意在不同的指令和组件之间共享信息.如何在两个多个组件之间共享信息呢. 最近在项目上,组件跟组件之间可能是父子关系,兄弟关系,爷孙关系都有.....我也找找了很多关于组件之间通讯的方法,不同的方法应用在不同的场景,根据功能需求选择组件之间最适合的通讯方式.下面我就总结一下关于组件通讯的N多种方法. 1.父→子 input parent.ts import { Component } from '@angular/core'; @Component({ selector: 'page-pa

  • Vue3中10多种组件通讯方法小结

    目录 Props emits expose / ref Non-Props 单个根元素的情况 多个元素的情况 v-model 单值的情况 多个 v-model 绑定 v-model 修饰符 插槽 slot 默认插槽 具名插槽 作用域插槽 provide / inject 总线 bus getCurrentInstance Vuex State Getter Mutation Action Module Pinia 安装 注册 mitt.js 安装 使用 本文讲解 Vue 3.2 组件多种通讯方式

  • JavaScript数组方法大全(推荐)

    数组在笔试中经常会出现的面试题,javascript中的数组与其他语言中的数组有些不同,为了方便之后数组的方法学习,下面小编给大家整理了关于数组的操作方法,一起看看吧. 数组创建 JavaScript中创建数组有两种方式,第一种是使用 Array 构造函数: var arr1 = new Array(); //创建一个空数组 var arr2 = new Array(20); // 创建一个包含20项的数组 var arr3 = new Array("lily","lucy&

  • vue的组件通讯方法总结大全

    目录 1.通过属性传值props

  • 小程序数据通信方法大全(推荐)

    序 本文论述的是子或孙向父传递数据的情况,自下而上 相信大家平时在小程序开发中肯定遇到过页面或者组件之间的数据通信问题,那小程序数据通信都有哪些方式呢?如何选择合适的通信方式呢?这就是本文要讨论的重点. 关系划分 在讨论都有哪些数据通信方式之前,我们先来定义一下,小程序页面.组件之间都有哪些关系.我总结了一下,大概分为以下3类: 父子关系 兄弟关系 爷孙关系 不同的关系里面,不同角色之间有可能是页面,也有可能是组件,接下来我们就一个个来揭示如何进行数据通信. 父子关系 父子关系一般主要就是两种情

  • ES6下子组件调用父组件的方法(推荐)

    出于某些目的,最近又开始研究起了RN,看着教程一步步的学习,在最近却是碰到了一个问题,那就是父子组件的方法调用的问题. 这个问题我百度了很久,JS的ES6语法下,用class创建组件,子组件调用父组件方法模拟器不断报错. 因为我看的视频是基于es5的语法来实现的代码,所以语法有些不同. es5的语法下,方法的this都是RN已经帮我们处理好了的,所以按照视频中的示例是可以达成效果的,但是es6貌似是要自己写的.. 具体的写法就是在constructor中添加 this.xxxxx = this.

  • springboot快速整合Mybatis组件的方法(推荐)

    Spring Boot简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,Spring Boot致力于在蓬勃发展的快速应用开发领域(rapid application development)成为领导者. 原有Spring优缺点分析 Spring的优点分析 Spring是Java企业版(Java Enterprise Edition,

  • Ajax学习笔记---3种Ajax的实现方法【推荐】

    Ajax:  Asynchronous JavaScript and Xml , 异步js脚本和xml , 常用来实现页面局部的异步刷新, 对提高用户体验有很大帮助. Xml在多语言时较有优势, 但Ajax技术实际上较多采用Json对象而不是Xml来处理数据. (一) Ajax历史....了解性知识 Ajax归属于Web前端开发技术, 与javascript有着异常紧密的联系. Ajax就是一种实现异步通信无刷新的技术, 而这种技术可以有很多种实现方式. 浏览器的鼻祖网景(NetScape)公司

  • vue3中的父子组件通讯详情

    目录 一.传统的props 二.通过modeValue绑定 三.事件广播(vue3中$on和$emit已废弃),使用新的插件mitt 一.传统的props 通过在父组件中给子组件传值,然后在子组件中通过props接受数据 //父组件 <ValidateInput type="text" v-model="emailVal" :rules='emailRules' placeholder='请输入邮箱地址' ref="inputRef" &g

  • Vue.js 父子组件通讯开发实例

    vue.js,是一个构建数据驱动的 web 界面的库.Vue.js 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件.(这是官方的一个解释!) 小编没使用过angularjs,也没使用过react.js,不能详细的说明三者的区别,想了解的话,在官方有一个分析,请点这里查看 小编从业前端开发也有了一年多的时间,刚开始的时候,前端开发展现的技术太多,小编有心无力,兼顾不过来,经过了解之后,还是选择了学原生js基础兼并jquery的学习上路.小编使用vue.js,也是因为业务的需求

随机推荐