


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!

本篇文章继续Angular的学习,带大家了解一下Angular中的元数据和装饰器,简单了解一下他们的用法,希望对大家有所帮助!

本篇文章带大家深入了解一下angular的状态管理器NgRx,介绍一下NgRx的使用方法,希望对大家有所帮助!

angular中怎么使用monaco-editor?下面本篇文章记录下最近的一次业务中用到的 monaco-editor 在 angular 中的使用,希望对大家有所帮助!

Angular项目过大,怎么合理拆分它?下面本篇文章给大家介绍一下合理拆分Angular项目的方法,希望对大家有所帮助!

本篇文章给大家分享一个Angular实战,了解一下angualr 结合 ng-zorro 如何快速开发一个后台系统,希望对大家有所帮助!

怎么自定义angular-datetime-picker格式?下面本篇文章聊聊自定义格式的方法,希望对大家有所帮助!

本篇文章带大家了解一下Angular中的独立组件,看看怎么在Angular中创建一个独立组件,怎么在独立组件中导入已有的模块,希望对大家有所帮助!

Angular Route中怎么提前获取数据?下面本篇文章给大家介绍一下从 Angular Route 中提前获取数据的方法,希望对大家有所帮助!


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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

WebStorm Mac version
Useful JavaScript development tools

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),
