搜索
首页web前端js教程带你了解Angular组件间进行通信的几种方法

Angular组件间怎么通信?下面本篇文章带大家了解一下Angular中组件通信的方法,希望对大家有所帮助!

带你了解Angular组件间进行通信的几种方法

上一篇,我们讲了 Angular 结合 NG-ZORRO 快速开发。前端开发,很大程度上是组件化开发,永远离不开组件之间的通信。那么,在 Angular 开发中,其组件之间的通信是怎么样的呢?【相关教程推荐:《angular教程》】

举一反三,VueReact 中大同小异

本文纯文字,比较枯燥。因为控制台打印的东西比较鸡肋,所以就不配图了,嗯~希望读者跟着说明代码走一遍更容易吸收~

1. 父组件通过属性传递值给子组件

相当于你自定义了一个属性,通过组件的引入,将值传递给子组件。Show you the CODE

<!-- parent.component.html -->

<app-child [parentProp]="&#39;My kid.&#39;"></app-child>

在父组件中调用子组件,这里命名一个 parentProp 的属性。

// child.component.ts

import { Component, OnInit, Input } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-child&#39;,
  templateUrl: &#39;./child.component.html&#39;,
  styleUrls: [&#39;./child.component.scss&#39;]
})
export class ChildComponent implements OnInit {
  // 输入装饰器
  @Input()
  parentProp!: string;

  constructor() { }

  ngOnInit(): void {
  }
}

子组件接受父组件传入的变量 parentProp,回填到页面。

<!-- child.component.html -->

<h1>Hello! {{ parentProp }}</h1>

2. 子组件通过 Emitter 事件传递信息给父组件

通过 new EventEmitter() 将子组件的数据传递给父组件。

// child.component.ts

import { Component, OnInit, Output, EventEmitter } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-child&#39;,
  templateUrl: &#39;./child.component.html&#39;,
  styleUrls: [&#39;./child.component.scss&#39;]
})
export class ChildComponent implements OnInit {
  // 输出装饰器
  @Output()
  private childSayHi = new EventEmitter()

  constructor() { }

  ngOnInit(): void {
    this.childSayHi.emit(&#39;My parents&#39;);
  }
}

通过 emit 通知父组件,父组件对事件进行监听。

// parent.component.ts

import { Component, OnInit } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-communicate&#39;,
  templateUrl: &#39;./communicate.component.html&#39;,
  styleUrls: [&#39;./communicate.component.scss&#39;]
})
export class CommunicateComponent implements OnInit {

  public msg:string = &#39;&#39;

  constructor() { }

  ngOnInit(): void {
  }

  fromChild(data: string) {
    // 这里使用异步
    setTimeout(() => {
      this.msg = data
    }, 50)
  }
}

在父组件中,我们对 child 组件来的数据进行监听后,这里采用了 setTimeout 的异步操作。是因为我们在子组件中初始化后就进行了 emit,这里的异步操作是防止 Race Condition 竞争出错。

我们还得在组件中添加 fromChild 这个方法,如下:

<!-- parent.component.html -->

<h1>Hello! {{ msg }}</h1>
<app-child (childSayHi)="fromChild($event)"></app-child>

3. 通过引用,父组件获取子组件的属性和方法

我们通过操纵引用的方式,获取子组件对象,然后对其属性和方法进行访问。

我们先设置子组件的演示内容:

// child.component.ts

import { Component, OnInit } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-child&#39;,
  templateUrl: &#39;./child.component.html&#39;,
  styleUrls: [&#39;./child.component.scss&#39;]
})
export class ChildComponent implements OnInit {

  // 子组件的属性
  public childMsg:string = &#39;Prop: message from child&#39;

  constructor() { }

  ngOnInit(): void {
    
  }

  // 子组件方法
  public childSayHi(): void {
    console.log(&#39;Method: I am your child.&#39;)
  }
}

我们在父组件上设置子组件的引用标识 #childComponent

<!-- parent.component.html -->

<app-child #childComponent></app-child>

之后在 javascript 文件上调用:

import { Component, OnInit, ViewChild } from &#39;@angular/core&#39;;
import { ChildComponent } from &#39;./components/child/child.component&#39;;

@Component({
  selector: &#39;app-communicate&#39;,
  templateUrl: &#39;./communicate.component.html&#39;,
  styleUrls: [&#39;./communicate.component.scss&#39;]
})
export class CommunicateComponent implements OnInit {
  @ViewChild(&#39;childComponent&#39;)
  childComponent!: ChildComponent;

  constructor() { }

  ngOnInit(): void {
    this.getChildPropAndMethod()
  }

  getChildPropAndMethod(): void {
    setTimeout(() => {
      console.log(this.childComponent.childMsg); // Prop: message from child
      this.childComponent.childSayHi(); // Method: I am your child.
    }, 50)
  }

}

这种方法有个限制?,就是子属性的修饰符需要是 public,当是 protected 或者 private 的时候,会报错。你可以将子组件的修饰符更改下尝试。报错的原因如下:

类型 使用范围
public 允许在累的内外被调用,作用范围最广
protected 允许在类内以及继承的子类中使用,作用范围适中
private 允许在类内部中使用,作用范围最窄

4. 通过 service 去变动

我们结合 rxjs 来演示。

rxjs 是使用 Observables 的响应式编程的库,它使编写异步或基于回调的代码更容易。

后期会有一篇文章记录 rxjs,敬请期待

我们先来创建一个名为 parent-and-child 的服务。

// parent-and-child.service.ts

import { Injectable } from &#39;@angular/core&#39;;
import { BehaviorSubject, Observable } from &#39;rxjs&#39;; // BehaviorSubject 有实时的作用,获取最新值

@Injectable({
  providedIn: &#39;root&#39;
})
export class ParentAndChildService {

  private subject$: BehaviorSubject<any> = new BehaviorSubject(null)

  constructor() { }
  
  // 将其变成可观察
  getMessage(): Observable<any> {
    return this.subject$.asObservable()
  }

  setMessage(msg: string) {
    this.subject$.next(msg);
  }
}

接着,我们在父子组件中引用,它们的信息是共享的。

// parent.component.ts

import { Component, OnDestroy, OnInit } from &#39;@angular/core&#39;;
// 引入服务
import { ParentAndChildService } from &#39;src/app/services/parent-and-child.service&#39;;
import { Subject } from &#39;rxjs&#39;
import { takeUntil } from &#39;rxjs/operators&#39;

@Component({
  selector: &#39;app-communicate&#39;,
  templateUrl: &#39;./communicate.component.html&#39;,
  styleUrls: [&#39;./communicate.component.scss&#39;]
})
export class CommunicateComponent implements OnInit, OnDestroy {
  unsubscribe$: Subject<boolean> = new Subject();

  constructor(
    private readonly parentAndChildService: ParentAndChildService
  ) { }

  ngOnInit(): void {
    this.parentAndChildService.getMessage()
      .pipe(
        takeUntil(this.unsubscribe$)
      )
      .subscribe({
        next: (msg: any) => {
          console.log(&#39;Parent: &#39; + msg); 
          // 刚进来打印 Parent: null
          // 一秒后打印 Parent: Jimmy
        }
      });
    setTimeout(() => {
      this.parentAndChildService.setMessage(&#39;Jimmy&#39;);
    }, 1000)
  }

  ngOnDestroy() {
    // 取消订阅
    this.unsubscribe$.next(true);
    this.unsubscribe$.complete();
  }
}
import { Component, OnInit } from &#39;@angular/core&#39;;
import { ParentAndChildService } from &#39;src/app/services/parent-and-child.service&#39;;

@Component({
  selector: &#39;app-child&#39;,
  templateUrl: &#39;./child.component.html&#39;,
  styleUrls: [&#39;./child.component.scss&#39;]
})
export class ChildComponent implements OnInit {
  constructor(
    private parentAndChildService: ParentAndChildService
  ) { }
  
  
  // 为了更好理解,这里我移除了父组件的 Subject
  ngOnInit(): void {
    this.parentAndChildService.getMessage()
      .subscribe({
        next: (msg: any) => {
          console.log(&#39;Child: &#39;+msg);
          // 刚进来打印 Child: null
          // 一秒后打印 Child: Jimmy
        }
      })
  }
}

在父组件中,我们一秒钟之后更改值。所以在父子组件中,一进来就会打印 msg 的初始值 null,然后过了一秒钟之后,就会打印更改的值 Jimmy。同理,如果你在子组件中对服务的信息,在子组件打印相关的值的同时,在父组件也会打印。更多编程相关知识,请访问:编程入门!!

以上是带你了解Angular组件间进行通信的几种方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:掘金社区。如有侵权,请联系admin@php.cn删除
聊聊Angular中的元数据(Metadata)和装饰器(Decorator)聊聊Angular中的元数据(Metadata)和装饰器(Decorator)Feb 28, 2022 am 11:10 AM

本篇文章继续Angular的学习,带大家了解一下Angular中的元数据和装饰器,简单了解一下他们的用法,希望对大家有所帮助!

angular学习之详解状态管理器NgRxangular学习之详解状态管理器NgRxMay 25, 2022 am 11:01 AM

本篇文章带大家深入了解一下angular的状态管理器NgRx,介绍一下NgRx的使用方法,希望对大家有所帮助!

浅析angular中怎么使用monaco-editor浅析angular中怎么使用monaco-editorOct 17, 2022 pm 08:04 PM

angular中怎么使用monaco-editor?下面本篇文章记录下最近的一次业务中用到的 monaco-editor 在 angular 中的使用,希望对大家有所帮助!

项目过大怎么办?如何合理拆分Angular项目?项目过大怎么办?如何合理拆分Angular项目?Jul 26, 2022 pm 07:18 PM

Angular项目过大,怎么合理拆分它?下面本篇文章给大家介绍一下合理拆分Angular项目的方法,希望对大家有所帮助!

聊聊自定义angular-datetime-picker格式的方法聊聊自定义angular-datetime-picker格式的方法Sep 08, 2022 pm 08:29 PM

怎么自定义angular-datetime-picker格式?下面本篇文章聊聊自定义格式的方法,希望对大家有所帮助!

Angular + NG-ZORRO快速开发一个后台系统Angular + NG-ZORRO快速开发一个后台系统Apr 21, 2022 am 10:45 AM

本篇文章给大家分享一个Angular实战,了解一下angualr 结合 ng-zorro 如何快速开发一个后台系统,希望对大家有所帮助!

聊聊Angular Route中怎么提前获取数据聊聊Angular Route中怎么提前获取数据Jul 13, 2022 pm 08:00 PM

Angular Route中怎么提前获取数据?下面本篇文章给大家介绍一下从 Angular Route 中提前获取数据的方法,希望对大家有所帮助!

浅析Angular中的独立组件,看看怎么使用浅析Angular中的独立组件,看看怎么使用Jun 23, 2022 pm 03:49 PM

本篇文章带大家了解一下Angular中的独立组件,看看怎么在Angular中创建一个独立组件,怎么在独立组件中导入已有的模块,希望对大家有所帮助!

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
3 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器