Home  >  Article  >  Web Front-end  >  Take you through several methods of communication between Angular components

Take you through several methods of communication between Angular components

青灯夜游
青灯夜游forward
2022-12-26 19:51:552024browse

AngularHow to communicate between components? The following article will take you through the method of component communication in Angular. I hope it will be helpful to you!

Take you through several methods of communication between Angular components

In the previous article, we talked about Angular combined with NG-ZORRO rapid development. Front-end development is largely component-based development and is always inseparable from communication between components. So, in Angular development, what is the communication between its components like? [Related tutorial recommendations: "angular tutorial"]

Draw inferences from one example, Vue and React are similar with minor differences

This article is pure text and relatively boring. Because the things printed by the console are relatively useless, I don’t include pictures. Hmm~ I hope readers can more easily absorb it by following the explanation code~

1. The parent component passes the value to the child component through attributes

It is equivalent to you customizing a property and passing the value to the sub-component through the introduction of the component. Show you the CODE.

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

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

Call the child component in the parent component, here name a parentProp attribute.

// 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 {
  }
}

The child component accepts the variable parentProp passed in by the parent component and backfills it to the page.

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

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

2. The child component passes information to the parent component through the Emitter event

Passes the data of the child component to the parent through new EventEmitter() components.

// 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;);
  }
}

Notifies the parent component through emit, and the parent component monitors the event.

// 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)
  }
}

In the parent component, after we monitor the data from the child component, we use the asynchronous operation of setTimeout. It's because we performed emit after initialization in the subcomponent. The asynchronous operation here is to prevent Race Condition competition errors.

We also have to add the fromChild method to the component, as follows:

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

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

3. Through references, the parent component obtains the properties and methods of the child component

We obtain the subcomponent object by manipulating the reference, and then access its properties and methods.

We first set the demo content of the child component:

// 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;)
  }
}

We set the reference identifier of the child component on the parent component #childComponent:

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

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

After Call on the javascript file:

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)
  }

}

Is there a limitation to this method? That is, the modifier of the sub-property needs to be public, when it is protected or private, an error will be reported. You can try changing the modifier of the subcomponent. The reason for the error is as follows:

Type Usage scope
public Allowed to be called inside and outside the tired, the widest scope
protected Allowed to be used within the class and inherited subclasses, the scope is moderate
private Allowed to be used inside a class, with the narrowest scope

4. To change

through service, we will demonstrate it with rxjs.

rxjs is a library for reactive programming using Observables, which makes it easier to write asynchronous or callback-based code.

There will be an article to record rxjs later, so stay tuned

Let’s first create a file named parent-and-child services.

// 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);
  }
}

Next, we reference it in the parent and child components, and their information is shared.

// 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
        }
      })
  }
}

In the parent component, we change the value after one second. So in the parent-child component, the initial value null of msg will be printed as soon as it comes in, and then after one second, the changed value Jimmy will be printed. . In the same way, if you provide service information in a child component, while the child component prints the relevant values, it will also be printed in the parent component. For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Take you through several methods of communication between Angular components. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete