Home  >  Article  >  Web Front-end  >  Introduction to 5 methods of component communication in Angular

Introduction to 5 methods of component communication in Angular

青灯夜游
青灯夜游forward
2020-09-11 10:28:562287browse

Introduction to 5 methods of component communication in Angular

Componentization is the core concept of Angular, so component communication is used more frequently and is very important.

Official portal:

https://angular.io/guide/component-interaction

https://angular.cn/guide/component- interaction

Related tutorial recommendations: "angular tutorial"

Parent-child component communication

Keywords Input Output EventEmitter ViewChild

1. Parent component passes data to child component

[Input]

How to bind properties

Parent component:

<!-- parentComponent -->
<app-child [name]="&#39;childName&#39;"></app-child>

Sub component:
// The sub component needs to use Input to receive

<span>{{name}}</span>
@Input() public name:string = &#39;&#39;;

2. The sub component sends a message to the parent Component passes data

[Output EventEmitter]

Child component:

@Output()
public readonly childEmit: EventEmitter<T> = new EventEmitter<T>();

this.childEmit.emit(data);

Parent component:

<app-child (childEmit)="getData($event)"></app-child>
public getData(data:T): void {  }

3. ViewChild method

Because I think this method can not only allow the parent component to obtain the data of the child component, but also allow the parent component to set variable values ​​​​for the child component, etc., so I separated it here separately.

Parent component:

<app-child **#child**></app-child>

<button (click)="**child**.print(&#39;---&#39;)">点击</button>
@ViewChild(&#39;child&#39;, { static: true })
public child!: ElementRef<HTMLElement>;

public print():void{
     if(this.child){
       // 这里得到child,可以使用child中的所有的public属性方法
       this.child.print(&#39;hello2&#39;);
     }
}

[Example]

// 父组件
import { Component } from &#39;@angular/core&#39;;

@Component({
  selector: &#39;app-parent&#39;,
  template: `
    <app-child #child [name]="name" (childEmit)="childClick($event)"></app-child>
    <button (click)="child.print(&#39;hello1&#39;)">调用子组件的方法1</button>
    <button (click)="print()">调用子组件的方法2</button>
  `
})

export class ParentComponent {

   public name:string = &#39;大儿子&#39;;
   @ViewChild(&#39;child&#39;, { static: true })
   public child!: ElementRef<HTMLElement>;

   public childClick(bool:Boolean):void{
      // TODO
   }

   public print():void{
      if(this.child){
        this.child.print(&#39;hello2&#39;);
     }
   }
}
/*****************************************************/
// 子组件

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

@Component({
  selector: &#39;app-child&#39;,
  template: `
    <h3 (click)="myClick()">{{name}}</h3>
  `
})

export class HeroChildComponent {
  @Input() 
  public name: string;

  @Output()
  public readonly childEmit: EventEmitter<boolean> = new EventEmitter<boolean>();

  public myClick():void{
    this.childEmit.emit(true);
  }

  public print(content:string):void{
    console.log(content);
  }
}

Non-parent-child component communication

1. Service

The singleton mode is actually a variable that requires two-way triggering (sending information/receiving information), and setting and obtaining data requires the component itself to handle it.

service.ts

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

@Injectable()

export class myService {
  public info: string = &#39;&#39;;
}

Component 1 transmits information to service

import { Service1 } from &#39;../../service/service1.service&#39;;
...

public constructor(
  public service: Service1,
) { }

public changeInfo():void {
  this.service.info = this.service.info + &#39;1234&#39;;
}
...

Component 2 obtains information from service

import { Service2 } from &#39;../../service/service2.service&#39;;
...

public constructor(
  public service: Service2,
) { }

public showInfo() {
  console.log(this.service.info);
}
...

2, Subject (publish Subscription)

The true publish-subscribe model, when the data changes, the subscriber can also get a response. Here are only examples of BehaviorSubject

// Service
import { BehaviorSubject } from &#39;rxjs&#39;;
...
public messageSource = new BehaviorSubject<string>(&#39;Start&#39;);
public changeMessage(message: string): void {
  this.messageSource.next(message);
}

public getMessageSource(): Observable<string> {
  return this.messageSource.asObservable();
}

/////////////////////////
// 发布
...
this.messageService.changeMessage(&#39;message change&#39;);
/////////////////////////
public 
// 订阅 (记得根据需要选择是否取消订阅 unsubscribe)
this.messageService.getMessageSource().subscribe(m => {
  console.log(m);
})

Comparison of four kinds of subject Subject

rxjs subject Whether to store data Whether an initial value is required When to publish data to subscribers
Subject No No Publish promptly. Publish when new data is available
BehaviorSubject Yes. Store the last piece of data or the initial value is and publish it in time. Release when new data is available
ReplaySubject Yes. Store all data No Publish in a timely manner. Publish when new data is available
AsyncSubject Yes. Storing the last piece of data is delayed release. Only when the data source is complete will it be released

Other communication methods

Routing value, browser local storage (LocalStorage, SessionStorage), cookie.

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of Introduction to 5 methods of component communication in Angular. For more information, please follow other related articles on the PHP Chinese website!

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