


How do Angular components communicate? 2 methods for parent-child component communication
This article will take you to understand the component communication in Angular, and introduce the methods of communication between parent and child components, and communication between components that have no direct relationship.
In actual applications, our components will be related in a tree structure, so the relationship between components is mainly:
【 Related tutorial recommendations: "angular tutorial"】
Father-son relationship
Brother relationship
No direct relationship
Prepare our environment:
1. Create a header
Components: ng g c components/header
<app-button></app-button> <app-title></app-title> <app-button></app-button>
export class HeaderComponent implements OnInit { constructor() {} ngOnInit(): void {} }
2. Create a title
component: ng g c components/title
<span>{{title}}</span>
export class TitleComponent implements OnInit { public title: string = '标题'; constructor() {} ngOnInit(): void {} }
3. Create a button
component: ng g c components/button
<button>{{ btnName }}</button>
export class ButtonComponent implements OnInit { public btnName: string = '按钮'; constructor() {} ngOnInit(): void {} }
Directly call
Applies to parent-child relationship components. Note that direct calls make the coupling of parent-child components higher. To make it clear, direct calls are required.
1. Mount our header component into the app so that a parent-child component relationship is formed between the app and the header.
2. Use # for us Give the component a name:
<app-header></app-header>
3. Now our header component is still very empty, let’s expand it, otherwise What to call?
export class HeaderComponent implements OnInit { public name: string = 'HeaderComponent'; printName(): void { console.log('component name is', this.name); } }
4. After the component is expanded, we can call the properties and functions in the sub-component header in the parent component app
<app-header #header></app-header> <p> 调用子组件属性: {{ header.name }} <button (click)="header.printName()">调用子组件函数</button> </p>
5. The fourth step is to The operation is performed in the html template of the component. Sometimes we also need to operate the sub-component in the ts class of the parent component. We will demonstrate next.
6. We need to use a new decorator@ViewChild(Component)
export class AppComponent { title = 'angular-course'; @ViewChild(HeaderComponent) private header!: HeaderComponent; // 声明周期钩子: 组件及子组件视图更新后调用,执行一次 ngAfterViewInit(): void { // 调用子组件属性 console.log(this.header.name); // 调用子组件函数 this.header.printName(); } }
@Input and @Output
Applicable to parent-child relationship components
1. We solve this problem by defining title
in the header
component. Direct calls in the coupled title
component lead to complex expansion problems
2. Add @Input() decoration to the title
attribute in the title
component Container: @Input() public title: string = 'Title';
3. Add a title attribute to the header component and assign a value: public title: string = 'I am New title';
4. We use the title
component in the html
template of the header
component like this: <app-title></app-title>
5. Let’s take a look at the effect so far. Although the interface is ugly, I will use the component next time Is it more convenient to set title
?
6. The above steps realize that the data of the parent component is passed to the child component, then let’s continue Let’s see how the data of the child component is passed to the parent component? Let’s use the @Output()
decorator to implement the following
7. In the title
component Add the titleChange
attribute to the ts class: @Output() public titleChange = new EventEmitter();
8. In the ts of the title
component Regularly dispatch data in the class
ngOnInit(): void { // 定时将子组件的数据进行派发 setInterval(() => { this.titleChange.emit(this.title); }, 1500); }
9. Now let’s modify the header parent component to receive the dispatched data:
<app-title [title]="title" (titleChange)="onChildTitleChange($event)"> </app-title>
onChildTitleChange(value: any) { console.log('onChildTitleChange: >>', value); }
Use service simple interest for communication
Applicable to components that have no direct relationship
1. Since we need to communicate through services, we first Create a service: ng g s services/EventBus
, and we declare an attribute of type Subject
to assist communication
@Injectable({ providedIn: 'root', }) export class EventBusService { public eventBus: Subject<any> = new Subject(); constructor() {} }
2. To save trouble, we will not The components have been re-created, because the button component and title component in our header
are components that have no direct relationship.
3. Transform our button
component and add a click event to trigger the triggerEventBus
function
export class ButtonComponent implements OnInit { public btnName: string = '按钮'; constructor(public eventBusService: EventBusService) {} ngOnInit(): void {} public triggerEventBus(): void { this.eventBusService.eventBus.next('我是按钮组件'); } }
4. In title
Acquisition of simulated data in components
export class TitleComponent implements OnInit { constructor(public eventBusService: EventBusService) {} ngOnInit(): void { this.eventBusService.eventBus.subscribe((value) => { console.log(value); }); } }
Use cookie, session or localstorage to communicate
1. This is very simple. We still use the title
component and the button
component for demonstration. This time we save the data in the title component. In Get data from the button
component. Let’s only demonstrate localstorage
, everything else is the same.
2. Save title
in the ngOnInit()
hook of the title
component to localstorage
: window.localStorage.setItem('title', this.title);
3. Get data in the button component: const title = window.localStorage.getItem('title');
Conclusion:
In this article we have introduced Angular’s component communication, so that our split components can perform reasonable Communication provides guarantee, and the use of components until now is done by introducing tags.
Original address: https://juejin.cn/post/6991471300837572638
Author: Xiaoxin
For more programming-related knowledge, please Visit: Introduction to Programming! !
The above is the detailed content of How do Angular components communicate? 2 methods for parent-child component communication. For more information, please follow other related articles on the PHP Chinese website!

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
