


Take you through several methods of communication between Angular components
AngularHow to communicate between components? The following article will take you through the method of component communication in Angular. I hope it will be helpful to you!
In the previous article, we talked about Angular combined with NG-ZORRO rapid development. Front-end development is largely component-based development and is always inseparable from communication between components. So, in Angular
development, what is the communication between its components like? [Related tutorial recommendations: "angular tutorial"]
Draw inferences from one example,
Vue
andReact
are similar with minor differences
This article is pure text and relatively boring. Because the things printed by the console are relatively useless, I don’t include pictures. Hmm~ I hope readers can more easily absorb it by following the explanation code~
1. The parent component passes the value to the child component through attributes
It is equivalent to you customizing a property and passing the value to the sub-component through the introduction of the component. Show you the CODE
.
<!-- parent.component.html --> <app-child [parentProp]="'My kid.'"></app-child>
Call the child component in the parent component, here name a parentProp
attribute.
// child.component.ts import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { // 输入装饰器 @Input() parentProp!: string; constructor() { } ngOnInit(): void { } }
The child component accepts the variable parentProp
passed in by the parent component and backfills it to the page.
<!-- child.component.html --> <h1 id="Hello-nbsp-nbsp-parentProp-nbsp">Hello! {{ parentProp }}</h1>
2. The child component passes information to the parent component through the Emitter event
Passes the data of the child component to the parent through new EventEmitter()
components.
// child.component.ts import { Component, OnInit, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { // 输出装饰器 @Output() private childSayHi = new EventEmitter() constructor() { } ngOnInit(): void { this.childSayHi.emit('My parents'); } }
Notifies the parent component through emit
, and the parent component monitors the event.
// parent.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-communicate', templateUrl: './communicate.component.html', styleUrls: ['./communicate.component.scss'] }) export class CommunicateComponent implements OnInit { public msg:string = '' constructor() { } ngOnInit(): void { } fromChild(data: string) { // 这里使用异步 setTimeout(() => { this.msg = data }, 50) } }
In the parent component, after we monitor the data from the child
component, we use the asynchronous operation of setTimeout
. It's because we performed emit
after initialization in the subcomponent. The asynchronous operation here is to prevent Race Condition
competition errors.
We also have to add the fromChild
method to the component, as follows:
<!-- parent.component.html --> <h1 id="Hello-nbsp-nbsp-msg-nbsp">Hello! {{ msg }}</h1> <app-child (childSayHi)="fromChild($event)"></app-child>
3. Through references, the parent component obtains the properties and methods of the child component
We obtain the subcomponent object by manipulating the reference, and then access its properties and methods.
We first set the demo content of the child component:
// child.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { // 子组件的属性 public childMsg:string = 'Prop: message from child' constructor() { } ngOnInit(): void { } // 子组件方法 public childSayHi(): void { console.log('Method: I am your child.') } }
We set the reference identifier of the child component on the parent component #childComponent
:
<!-- parent.component.html --> <app-child #childComponent></app-child>
After Call on the javascript
file:
import { Component, OnInit, ViewChild } from '@angular/core'; import { ChildComponent } from './components/child/child.component'; @Component({ selector: 'app-communicate', templateUrl: './communicate.component.html', styleUrls: ['./communicate.component.scss'] }) export class CommunicateComponent implements OnInit { @ViewChild('childComponent') childComponent!: ChildComponent; constructor() { } ngOnInit(): void { this.getChildPropAndMethod() } getChildPropAndMethod(): void { setTimeout(() => { console.log(this.childComponent.childMsg); // Prop: message from child this.childComponent.childSayHi(); // Method: I am your child. }, 50) } }
Is there a limitation to this method? That is, the modifier of the sub-property needs to be public
, when it is protected
or private
, an error will be reported. You can try changing the modifier of the subcomponent. The reason for the error is as follows:
Type | Usage scope |
---|---|
public | Allowed to be called inside and outside the tired, the widest scope |
protected | Allowed to be used within the class and inherited subclasses, the scope is moderate |
private | Allowed to be used inside a class, with the narrowest scope |
4. To change
through service, we will demonstrate it with rxjs
.
rxjs is a library for reactive programming using Observables
, which makes it easier to write asynchronous or callback-based code.
There will be an article to record
rxjs
later, so stay tuned
Let’s first create a file named parent-and-child
services.
// parent-and-child.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; // BehaviorSubject 有实时的作用,获取最新值 @Injectable({ providedIn: 'root' }) export class ParentAndChildService { private subject$: BehaviorSubject<any> = new BehaviorSubject(null) constructor() { } // 将其变成可观察 getMessage(): Observable<any> { return this.subject$.asObservable() } setMessage(msg: string) { this.subject$.next(msg); } }
Next, we reference it in the parent and child components, and their information is shared.
// parent.component.ts import { Component, OnDestroy, OnInit } from '@angular/core'; // 引入服务 import { ParentAndChildService } from 'src/app/services/parent-and-child.service'; import { Subject } from 'rxjs' import { takeUntil } from 'rxjs/operators' @Component({ selector: 'app-communicate', templateUrl: './communicate.component.html', styleUrls: ['./communicate.component.scss'] }) export class CommunicateComponent implements OnInit, OnDestroy { unsubscribe$: Subject<boolean> = new Subject(); constructor( private readonly parentAndChildService: ParentAndChildService ) { } ngOnInit(): void { this.parentAndChildService.getMessage() .pipe( takeUntil(this.unsubscribe$) ) .subscribe({ next: (msg: any) => { console.log('Parent: ' + msg); // 刚进来打印 Parent: null // 一秒后打印 Parent: Jimmy } }); setTimeout(() => { this.parentAndChildService.setMessage('Jimmy'); }, 1000) } ngOnDestroy() { // 取消订阅 this.unsubscribe$.next(true); this.unsubscribe$.complete(); } }
import { Component, OnInit } from '@angular/core'; import { ParentAndChildService } from 'src/app/services/parent-and-child.service'; @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { constructor( private parentAndChildService: ParentAndChildService ) { } // 为了更好理解,这里我移除了父组件的 Subject ngOnInit(): void { this.parentAndChildService.getMessage() .subscribe({ next: (msg: any) => { console.log('Child: '+msg); // 刚进来打印 Child: null // 一秒后打印 Child: Jimmy } }) } }
In the parent component, we change the value after one second. So in the parent-child component, the initial value null
of msg
will be printed as soon as it comes in, and then after one second, the changed value Jimmy
will be printed. . In the same way, if you provide service information in a child component, while the child component prints the relevant values, it will also be printed in the parent component. For more programming-related knowledge, please visit: Introduction to Programming! !
The above is the detailed content of Take you through several methods of communication between Angular components. For more information, please follow other related articles on the PHP Chinese website!

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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.

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.


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

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.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.

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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft