Angular 组件通信

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

image.png


一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第8天,点击查看活动详情


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


举一反三,VueReact 中大同小异


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


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



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


<!-- parent.component.html -->
<app-child [parentProp]="'My kid.'"></app-child>
复制代码


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


// child.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
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 '@angular/core';
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
  // 输出装饰器
  @Output()
  private childSayHi = new EventEmitter()
  constructor() { }
  ngOnInit(): void {
    this.childSayHi.emit('My parents');
  }
}
复制代码


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


// parent.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-communicate',
  templateUrl: './communicate.component.html',
  styleUrls: ['./communicate.component.scss']
})
export class CommunicateComponent implements OnInit {
  public msg:string = ''
  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 '@angular/core';
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {
  // 子组件的属性
  public childMsg:string = 'Prop: message from child'
  constructor() { }
  ngOnInit(): void {
  }
  // 子组件方法
  public childSayHi(): void {
    console.log('Method: I am your child.')
  }
}
复制代码


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


<!-- parent.component.html -->
<app-child #childComponent></app-child>
复制代码


之后在 javascript 文件上调用:


import { Component, OnInit, ViewChild } from '@angular/core';
import { ChildComponent } from './components/child/child.component';
@Component({
  selector: 'app-communicate',
  templateUrl: './communicate.component.html',
  styleUrls: ['./communicate.component.scss']
})
export class CommunicateComponent implements OnInit {
  @ViewChild('childComponent')
  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 '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs'; // BehaviorSubject 有实时的作用,获取最新值
@Injectable({
  providedIn: 'root'
})
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 '@angular/core';
// 引入服务
import { ParentAndChildService } from 'src/app/services/parent-and-child.service';
import { Subject } from 'rxjs'
import { takeUntil } from 'rxjs/operators'
@Component({
  selector: 'app-communicate',
  templateUrl: './communicate.component.html',
  styleUrls: ['./communicate.component.scss']
})
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('Parent: ' + msg); 
          // 刚进来打印 Parent: null
          // 一秒后打印 Parent: Jimmy
        }
      });
    setTimeout(() => {
      this.parentAndChildService.setMessage('Jimmy');
    }, 1000)
  }
  ngOnDestroy() {
    // 取消订阅
    this.unsubscribe$.next(true);
    this.unsubscribe$.complete();
  }
}
复制代码


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


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



相关文章
|
11天前
|
JavaScript
Angular使用@Input和@Output实现父子组件互相传参(类似Vue的props和this.emit)
Angular使用@Input和@Output实现父子组件互相传参(类似Vue的props和this.emit)
|
3月前
|
前端开发 JavaScript
Angular 组件模版代码里使用 ngIf 进行条件渲染的例子
Angular 组件模版代码里使用 ngIf 进行条件渲染的例子
21 0
|
4月前
Angular多个页面引入同一个组件报错The Component ‘MyComponentComponent‘ is declared by more than one NgModule怎么办?
Angular多个页面引入同一个组件报错The Component ‘MyComponentComponent‘ is declared by more than one NgModule怎么办?
|
4月前
快速创建Angular组件并定义传参、绑定自定义事件的方法
快速创建Angular组件并定义传参、绑定自定义事件的方法
|
7月前
|
前端开发 容器
使用 Rxjs 解决 Angular Component 之间的通信问题
使用 Rxjs 解决 Angular Component 之间的通信问题
35 0
|
8月前
|
JavaScript 定位技术
Angular1.x入门级自定义组件(导航条)
Angular1.x入门级自定义组件(导航条)
|
12月前
|
资源调度 JavaScript 容器
Angular封装WangEditor富文本组件
Angular封装WangEditor富文本组件
204 0
|
12月前
|
资源调度 前端开发 Java
使用Angular CDK实现一个Service弹出Toast组件
使用Angular CDK实现一个Service弹出Toast组件
88 0
|
12月前
|
JavaScript 前端开发 API
让Angular自定义组件支持form表单验证
让Angular自定义组件支持form表单验证
114 0
Angular组件传参
Input 是属性装饰器,用来定义组件内的输入属性。在实际应用场合,我们主要用来实现父组件向子组件传递数据。Angular 应用是由各式各样的组件组成,当应用启动时,Angular 会从根组件开始启动,并解析整棵组件树,数据由上而下流下下一级子组件。

热门文章

最新文章