Home > Article > Web Front-end > 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"
Keywords Input Output EventEmitter ViewChild
1. Parent component passes data to child component
[Input]
How to bind properties
Parent component:
<!-- parentComponent --> <app-child [name]="'childName'"></app-child>
Sub component:
// The sub component needs to use Input to receive
<span>{{name}}</span>
@Input() public name:string = '';
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('---')">点击</button>
@ViewChild('child', { static: true }) public child!: ElementRef<HTMLElement>; public print():void{ if(this.child){ // 这里得到child,可以使用child中的所有的public属性方法 this.child.print('hello2'); } }
[Example]
// 父组件 import { Component } from '@angular/core'; @Component({ selector: 'app-parent', template: ` <app-child #child [name]="name" (childEmit)="childClick($event)"></app-child> <button (click)="child.print('hello1')">调用子组件的方法1</button> <button (click)="print()">调用子组件的方法2</button> ` }) export class ParentComponent { public name:string = '大儿子'; @ViewChild('child', { static: true }) public child!: ElementRef<HTMLElement>; public childClick(bool:Boolean):void{ // TODO } public print():void{ if(this.child){ this.child.print('hello2'); } } } /*****************************************************/ // 子组件 import { Component, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', 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); } }
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 '@angular/core'; @Injectable() export class myService { public info: string = ''; }
Component 1 transmits information to service
import { Service1 } from '../../service/service1.service'; ... public constructor( public service: Service1, ) { } public changeInfo():void { this.service.info = this.service.info + '1234'; } ...
Component 2 obtains information from service
import { Service2 } from '../../service/service2.service'; ... 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 'rxjs'; ... public messageSource = new BehaviorSubject<string>('Start'); public changeMessage(message: string): void { this.messageSource.next(message); } public getMessageSource(): Observable<string> { return this.messageSource.asObservable(); } ///////////////////////// // 发布 ... this.messageService.changeMessage('message change'); ///////////////////////// public // 订阅 (记得根据需要选择是否取消订阅 unsubscribe) this.messageService.getMessageSource().subscribe(m => { console.log(m); })
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 |
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!