


A brief discussion on 5 methods of communication between Angular components
How to communicate between Angular components? The following article will introduce to you 5 methods of communication between Angular components. If necessary, you can refer to it~
Components are built by angular Unit, in order to ensure that data can be transferred back and forth between components in the project, Angular encapsulates some methods that can achieve communication between components. [Related tutorial recommendations: "angular tutorial"]
1. The parent component passes data to the child component through input binding
Parent component
parent.component.ts
age = 18; name = ' xiaoming '
parent.component.html
<app-child-1 [age]="age" [name]="name"></app-child-1>
Child component
child1.component.ts
@Input() age!: number;
Interception of changes in input attribute values
1. Use an input attribute setter to intercept the parent Changes in value in the component and take action.
child1.component.ts
@Input() set name(name: string) { this._name = name.trim(); } private _name: string;
2. Use the ngOnChanges() hook function to monitor changes in input attribute values and respond. This method is more appropriate than using property setters when multiple, interactive input properties need to be monitored.
child1.component.ts
ngOnChanges(changes: SimpleChanges): void { console.log(changes); }
We can learn about the related properties of SimpleChange through the type description file officially provided by angular:
2. The parent component listens to the event of the child component and obtains the value passed by the child component to the parent component
The child component exposes an EventEmitter (decorated with @Output (or) attribute. When an event occurs, the child component uses this attribute to emit the event to emit the value to the parent component. The parent component binds to this event property and responds when the event occurs.
Child component
child1.component.ts
@Output() voted = new EventEmitter<boolean>(); emitValue(): void { this.voted.emit(true); }
child1.component.html
<button (click)="emitValue()">Click</button>
Parent component
parent.component.html
<app-child-1 [age]="age" [name]="name" (voted)="getChildParam($event)"></app-child-1>
parent.component.ts
getChildParam(value: boolean): void { console.log(value); // true }
3. The parent component is read in the template through local variables (#varibleName) Get the properties of the child component and call the method of the child component
Child component
child1.component.ts
address = 'Shanghai'; setAddress(address: string): void { this.address = address; }
Parent Component
parent.component.html
<app-child-1 [age]="age" [name]="name" (voted)="getChildParam($event)" #child1Component></app-child-1> <div>{{child1Component.address}}</div> <button (click)="child1Component.setAddress('Beijing')">Click</button>
Limitations: Parent component-child component connections must all be made in the template of the parent component. If the class of the parent component needs to read the property value of the child component or call the method of the child component, it cannot use the local variable method.
4. The parent component calls @ViewChild
When the class of the parent component needs to read the property value of the child component or call the method of the child component, it cannot use local variables. Method; if there is such a need, we can inject the child component into the parent component through @ViewChild;
parent component
parent.component.ts
@ViewChild(Child1Component) private child1Component!: Child1Component;
You can access the properties and methods of child components through the child1Component variable;
5. Use shared services to achieve communication between any components
In order to achieve any For communication between components, we can combine the BehaviorSubject object in Rxjs to create a shared service; for the use of BehaviorSubject, please refer to this blogblog.tcs-y.com/2019/10/08/…
Create dataService.ts
import {BehaviorSubject} from 'rxjs'; import { Injectable} from '@angular/core'; @Injectable( {providedIn: 'root'} ) export class DataService { data: BehaviorSubject<number> = new BehaviorSubject<number>(0); }
Inject the service in the constructor of component 1 and set data
child1.component.ts
constructor(private dataService: DataService) {} // 设置data的值 changeData(): void { this.dataService.data.next(10); }
child1.component. html
<button (click)="changeData()">Click</button>
Inject the service in the constructor of component 2 and subscribe to data
child2.component.ts
constructor(private dataService: DataService) { this.dataService.data.subscribe(value => { console.log(value); // 10 }); }
For more programming-related knowledge, please visit: Introduction to programming! !
The above is the detailed content of A brief discussion on 5 methods of communication between Angular components. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

How to use monaco-editor in angular? The following article records the use of monaco-editor in angular that was used in a recent business. I hope it will be helpful to everyone!

Do you know Angular Universal? It can help the website provide better SEO support!

With the rapid development of the Internet, front-end development technology is also constantly improving and iterating. PHP and Angular are two technologies widely used in front-end development. PHP is a server-side scripting language that can handle tasks such as processing forms, generating dynamic pages, and managing access permissions. Angular is a JavaScript framework that can be used to develop single-page applications and build componentized web applications. This article will introduce how to use PHP and Angular for front-end development, and how to combine them

This article will give you an in-depth understanding of Angular's state manager NgRx and introduce how to use NgRx. I hope it will be helpful to you!

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

This article will take you through the independent components in Angular, how to create an independent component in Angular, and how to import existing modules into the independent component. I hope it will be helpful to you!

The Angular project is too large, how to split it reasonably? The following article will introduce to you how to reasonably split Angular projects. I hope it will be helpful to you!
