【Angular】Angula6中的组件通信

栏目: JavaScript · 发布时间: 6年前

内容简介:本文主要介绍 Angular6 中的组件通信父组件绑定信息

Angula6_组件通信

本文主要介绍 Angular6 中的组件通信

【Angular】Angula6中的组件通信

一、父子组件通信

1.1 父组件向子组件传递信息

方法一 在父组件上设置子组件的属性

父组件绑定信息

<app-child childTitle="可设置子组件标题"></app-child>

子组件接收消息

import { Component, OnInit, Input } from '@angular/core';
@Input childTitle: string;

方法二 父组件调用子组件的方法

父组件触发消息

<app-child #child></app-child> <button (click)="child.childPrint()"></button>

子组件接收消息

childPrint() {
  alert("来自子组件的打印");
}

1.2 子组件向父组件传递信息

方法一 使用 EventEmitter

子组件使用 EventEmitter 传递消息

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
...
@Output() initEmit = new EventEmitter<string>();
ngOnInit() {
  this.initEmit.emit("子组件初始化成功");
}
...

父组件接收消息

<app-child (initEmit)="accept($event)"></app-child>
accept(msg:string) {
  alert(msg);
}

方法二 使用 ViewChild

子组件提供传递参数的函数

sendInfo() {
  return 'Message from child 1.';
}

父组件使用 ViewChild 触发并接收信息

<button (click)="getInfo()">获取子组件1号的信息</button>
<h2>{{ info }}</h2>
import { Component, OnInit, ViewChild } from '@angular/core';
...
@ViewChild(ChildFirstComponent) private childcomponent: ChildFirstComponent;
getInfo() {
  this.info = this.childcomponent.sendInfo();
}

二、非父子组件通信

方法一 service

【Angular】Angula6中的组件通信

缺点:需要双向的触发(发送信息 / 接收信息)

service.ts

import { Component, Injectable, EventEmitter } from "@angular/core";
@Injectable()
export class myService {
  public info: string = "";
  constructor() {}
}

组件 1 向 service 传递信息

import { myService } from '../../service/myService.service';
...
constructor(
  public service: myService
) { }

changeInfo() {
  this.service.info = this.service.info + "1234";
}
...

组件 2 从 service 获取信息

import { myService } from '../../service/myService.service';
...
constructor(
  public service: myService
) { }

showInfo() {
  alert(this.service.info);
}
...

方法二 使用 BehaviorSubject

优点:真正的发布订阅模式,当数据改变时,订阅者也能得到响应

service

import { BehaviorSubject } from 'rxjs';
...
public messageSource = new BehaviorSubject<string>('Start');
changemessage(message: string): void {
  this.messageSource.next(message);
}

组件调用 service 的方法传信息和接收信息

changeInfo() {
  this.communication.changemessage('Message from child 1.');
}
ngOnInit() {
  this.communication.messageSource.subscribe(Message => {
    window.alert(Message);
    this.info = Message;
  });
}

三、其他的通信方式

  1. 路由传值
  2. cookie、session、storage

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

精通正则表达式

精通正则表达式

[美] Jeffrey E.F.Friedl / 余晟 / 电子工业出版社 / 2012-7 / 89.00元

《精通正则表达式(第3版)》内容简介:随着互联网的迅速发展,几乎所有工具软件和程序语言都支持的正则表达式也变得越来越强大和易于使用。《精通正则表达式(第3版)》是讲解正则表达式的经典之作。《精通正则表达式(第3版)》主要讲解了正则表达式的特性和流派、匹配原理、优化原则、实用诀窍以及调校措施,并详细介绍了正则表达式在Perl、Java、.NET、PHP中的用法。《精通正则表达式(第3版)》自第1版开......一起来看看 《精通正则表达式》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器