


How do Angular components interact with each other? Introduction to common interaction methods
The interaction between components is mainly between master and slave components. So how do Angular components interact with each other? The following article will introduce to you the common interaction methods between Angular components.
[Related tutorial recommendation: "angular tutorial"]
1. Binding through input type Pass data from parent component to child component
child.component.ts
export class ChildComponent implements OnInit { @Input() hero: any; @Input('master') masterName: string; // 第二个 @Input 为子组件的属性名 masterName 指定一个别名 master constructor() { } ngOnInit(): void { } }
child.component.html
<div style="background-color: #749f84"> <p>child works!</p> <h3 id="hero-name-nbsp-says">{{hero?.name}} says:</h3> <p>I, {{hero?.name}}, am at your service, {{masterName}}.</p> </div>
parent.component.ts
export class ParentComponent implements OnInit { hero = {name: 'qxj'} master = 'Master' constructor() { } ngOnInit(): void { } }
parent.component.html
<app-child [hero]="hero" [master]="master"></app-child>
2. The parent component listens to the events of the child component
child.component. ts
export class ChildComponent implements OnInit { @Input() name: string; @Output() voted = new EventEmitter<boolean>(); didVote = false; vote(agreed: boolean) { this.voted.emit(agreed); this.didVote = true; } constructor() { } ngOnInit(): void { } }
child.component.html
<h4 id="name">{{name}}</h4> <button (click)="vote(true)" [disabled]="didVote">Agree</button> <button (click)="vote(false)" [disabled]="didVote">Disagree</button>
parent.component.ts
export class ParentComponent implements OnInit { agreed = 0 disagreed = 0 voters = ['Narco', 'Celeritas', 'Bombasto'] onVoted(agreed: boolean) { agreed ? this.agreed++ : this.disagreed++ } constructor() { } ngOnInit(): void { } }
parent.component.html
<h2 id="Should-nbsp-mankind-nbsp-colonize-nbsp-the-nbsp-Universe">Should mankind colonize the Universe?</h2> <h3 id="Agree-nbsp-agreed-nbsp-Disagree-nbsp-disagreed">Agree: {{agreed}}, Disagree: {{disagreed}}</h3> <app-child *ngFor="let voter of voters" [name]="voter" (voted)="onVoted($event)"></app-child>
3. Parent component and child component interact through local variables
Parent component cannot use data binding to read child components Properties or methods to call subcomponents. However, you can create a new local variable in the parent component template to represent the child component, and then use this variable to read the properties of the child component and call the method of the child component, as shown in the following example.
Subcomponent CountdownTimerComponent
Countdown and launch a missile when it reaches zero. The start
and stop
methods are responsible for controlling the clock and displaying the countdown status information in the template.
child.component.ts
export class ChildComponent implements OnInit, OnDestroy { intervalId = 0 message = '' seconds = 11 clearTimer() { clearInterval(this.intervalId) } ngOnInit() { this.start() } ngOnDestroy() { this.clearTimer() } start() { this.countDown() } stop() { this.clearTimer() this.message = `Holding at T-${this.seconds} seconds` } private countDown() { this.clearTimer() this.intervalId = window.setInterval(() => { this.seconds -= 1 if (this.seconds === 0) { this.message = 'Blast off!' } else { if (this.seconds < 0) { this.seconds = 10 } // reset this.message = `T-${this.seconds} seconds and counting` } }, 1000) } }
child.component.html
<p>{{message}}</p>
parent.component.ts
export class ParentComponent implements OnInit { constructor() { } ngOnInit(): void { } }
parent.component.html
<h3 id="Countdown-nbsp-to-nbsp-Liftoff-nbsp-via-nbsp-local-nbsp-variable">Countdown to Liftoff (via local variable)</h3> <button (click)="child.start()">Start</button> <button (click)="child.stop()">Stop</button> <div class="seconds">{{child.seconds}}</div> <app-child #child></app-child>
4. The parent component calls <span style="font-size: 16px;">@ViewChild()</span>
This local variable method is a simple and convenient method. But it also has limitations, because parent component-child component connections must all be made in the template of the parent component. The code of the parent component itself has no access to the child components.
If the class of the parent component needs to read the property value of the subcomponent or call the method of the subcomponent, the local variable method cannot be used.
When the parent component class needs this access, the child component can be used as ViewChild and ***inject*** into the parent component.
countdown-parent.component.ts
import {AfterViewInit, Component, ViewChild} from '@angular/core' import {ChildComponent} from '../child/child.component' @Component({ selector: 'app-parent-vc', template: ` <h3 id="Countdown-nbsp-to-nbsp-Liftoff-nbsp-via-nbsp-ViewChild">Countdown to Liftoff (via ViewChild)</h3> <button (click)="start()">Start</button> <button (click)="stop()">Stop</button> <div class="seconds">{{ seconds() }}</div> <app-child></app-child> `, }) export class CountdownParentComponent implements AfterViewInit { @ViewChild(ChildComponent) private timerComponent: ChildComponent seconds() { return 0 } ngAfterViewInit() { // Redefine `seconds()` to get from the `ChildComponent.seconds` ... // but wait a tick first to avoid one-time devMode // unidirectional-data-flow-violation error setTimeout(() => { this.seconds = () => this.timerComponent.seconds }, 0) } start() { this.timerComponent.start() } stop() { this.timerComponent.stop() } }
For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of How do Angular components interact with each other? Introduction to common interaction methods. 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

AI Hentai Generator
Generate AI Hentai for free.

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



This article continues the learning of Angular, takes you to understand the metadata and decorators in Angular, and briefly understands their usage. I hope it will be helpful to everyone!

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

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!

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!

This article will share with you an Angular practical experience and learn how to quickly develop a backend system using angualr combined with ng-zorro. I hope it will be helpful to everyone!

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 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!
