search
HomeWeb Front-endJS TutorialHow 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.

How do Angular components communicate? 2 methods for parent-child component communication

In actual applications, our components will be related in a tree structure, so the relationship between components is mainly:

  • Father-son relationship

  • Brother relationship

  • No direct relationship

【 Related tutorial recommendations: "angular tutorial"】

Prepare our environment:

1. Create a headerComponents: 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 = &#39;标题&#39;;

  constructor() {}

  ngOnInit(): void {}
}

3. Create a button component: ng g c components/button

<button>{{ btnName }}</button>
export class ButtonComponent implements OnInit {
  public btnName: string = &#39;按钮&#39;;

  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 = &#39;HeaderComponent&#39;;

  printName(): void {
    console.log(&#39;component name is&#39;, 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 = &#39;angular-course&#39;;

  @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?

How do Angular components communicate? 2 methods for parent-child component communication

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(&#39;onChildTitleChange: >>&#39;, value);
}

Use service simple interest for communication

Applicable to components that have no direct relationship

How do Angular components communicate? 2 methods for parent-child component communication

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: &#39;root&#39;,
})
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 = &#39;按钮&#39;;

  constructor(public eventBusService: EventBusService) {}

  ngOnInit(): void {}

  public triggerEventBus(): void {
    this.eventBusService.eventBus.next(&#39;我是按钮组件&#39;);
  }
}

4. In titleAcquisition 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

How do Angular components communicate? 2 methods for parent-child component communication

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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft