Table of Contents
1. The parent component passes data to the child component through input binding
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
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
4. The parent component calls @ViewChild
5. Use shared services to achieve communication between any components
Home Web Front-end JS Tutorial A brief discussion on 5 methods of communication between Angular components

A brief discussion on 5 methods of communication between Angular components

Aug 16, 2021 am 10:04 AM
angular Component communication

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~

A brief discussion on 5 methods of communication between Angular components

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 '
Copy after login

parent.component.html

<app-child-1 [age]="age" [name]="name"></app-child-1>
Copy after login

Child component

child1.component.ts

@Input() age!: number;
Copy after login

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;
Copy after login

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);
}
Copy after login

We can learn about the related properties of SimpleChange through the type description file officially provided by angular:

A brief discussion on 5 methods of communication between Angular components

A brief discussion on 5 methods of communication between Angular components

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);
}
Copy after login

child1.component.html

<button (click)="emitValue()">Click</button>
Copy after login

Parent component

parent.component.html

<app-child-1 [age]="age" [name]="name" (voted)="getChildParam($event)"></app-child-1>
Copy after login

parent.component.ts

getChildParam(value: boolean): void {
    console.log(value); // true
}
Copy after login

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 = &#39;Shanghai&#39;;
setAddress(address: string): void {
    this.address = address;
}
Copy after login

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(&#39;Beijing&#39;)">Click</button>
Copy after login

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;
Copy after login

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 &#39;rxjs&#39;;
import { Injectable} from &#39;@angular/core&#39;;
@Injectable(
  {providedIn: &#39;root&#39;}
)
export class DataService {
  data: BehaviorSubject<number> = new BehaviorSubject<number>(0);
}
Copy after login

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);
}
Copy after login

child1.component. html

<button (click)="changeData()">Click</button>
Copy after login

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
    });
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

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

A brief analysis of how to use monaco-editor in angular A brief analysis of how to use monaco-editor in angular Oct 17, 2022 pm 08:04 PM

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!

An article exploring server-side rendering (SSR) in Angular An article exploring server-side rendering (SSR) in Angular Dec 27, 2022 pm 07:24 PM

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

How to use PHP and Angular for front-end development How to use PHP and Angular for front-end development May 11, 2023 pm 04:04 PM

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

Detailed explanation of angular learning state manager NgRx Detailed explanation of angular learning state manager NgRx May 25, 2022 am 11:01 AM

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!

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

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

A brief analysis of independent components in Angular and see how to use them A brief analysis of independent components in Angular and see how to use them Jun 23, 2022 pm 03:49 PM

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!

What should I do if the project is too big? How to split Angular projects reasonably? What should I do if the project is too big? How to split Angular projects reasonably? Jul 26, 2022 pm 07:18 PM

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!

See all articles