Detailed explanation of Angular parent-child component communication

Detailed explanation of Angular parent-child component communication

Overview

Angular component communication

Component tree, number 1 is the root component AppComponent.

Components are loosely coupled, and the less they know about each other, the better.

Clicking the button in component 4 triggers the initialization logic of component 5.

Traditional approach: Call the method of component 5 in the click event of button 4. Tight coupling.

Angular: Implemented without component 4 knowing component 5 exists at all.

Use loose coupling to pass data between components to develop highly reusable components.

Use input and output properties to pass data between components in a parent-child relationship.

1. Overview of input and output properties

Components are designed as black-box models, using input properties to declare what they receive from the outside world. There is no need to know where these things come from.

A component only needs to know what to do when the outside world provides it with what it needs.

Components emit events through output properties to tell the outside world something that might be of interest. There is no need to know to which component the event is emitted.

Anyone who is interested can subscribe to the events emitted by the component.

2. Input attributes

The subcomponent defines two input properties, which are decorated with the @Input() decorator.

@Input()
  stockCode: string;
  @Input()
  amount:number;

The parent component binds the stock attribute to the stockCode attribute of the child component by binding the attribute to the child component input attribute.

<div>
  I am the parent component</div>
<div>
  <input type="text" [(ngModel)]="stock" placeholder="Please enter the stock code">
  <app-order [stockCode]=stock [amount]="100"></app-order>
</div>

3. Property binding is one-way, from parent component to child component

Reset the value of the subcomponent's stockCode to Apple every 3 seconds.

export class OrderComponent implements OnInit {

  @Input()
  stockCode: string;
  @Input()
  amount:number;

  constructor() { 
    setInterval(()=>{
      this.stockCode = 'Apple'
    },3000)
  }

  ngOnInit() {
  }
}

When the value of the child component's stockCode changes to Apple, the value of the parent component's stock does not change. This means that the binding is one-way. Only the parent component can change the child component, and changes to the child component's properties will not affect the parent component.

4. Output properties

Angular components can use EventEmitter objects to emit custom events, which can be handled by other components. EventEmitter is a subclass of the Subject class in Rxjs. In responsive programming, it can be used as both an observer and an observer. That is to say, the EventEmitter object can emit custom events through its emit method, and can also subscribe to the event stream emitted by EventEmitter through the subscribe method.

How to use EventEmit to emit events from within a component?

Example scenario: Quote component

Suppose you need a component that can connect to a stock exchange and display the changing stock prices in real time. In order to make this component reusable in different financial applications, in addition to displaying the stock prices in real time, the component should also send the latest stock prices to the outside of the component so that other components can execute corresponding business logic based on the changing stock prices.

Note: It is a good practice to explicitly define specific data structures using classes or interfaces.

1. First simulate a real-time change in IBM's stock price

export class PriceQuoteComponent implements OnInit {

  //Do not connect to the stock service, use a random number generator to simulate the stock price changes, and display the stock code and the latest price stockCode:string="IBM";
  price:number;

  constructor() {
    setInterval(()=>{
      let priceQuote:PriceQuote = new PriceQuote(this.stockCode,100*Math.random());
      this.price=priceQuote.lastPrice;
    },1000)
  }

  ngOnInit() {
  }

}


//Encapsulate a quote object to encapsulate stock price information //It is a good habit to clearly define specific data structures with classes or interfaces export class PriceQuote {
  constructor(public stockCode: string, //stock code public lastPrice: number //latest price) {
  }
}

2. Output the information and tell the outside world who is interested to subscribe

The type behind EventEmit is the type of data in the event being emitted.

import { Component, OnInit, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-price-quote',
  templateUrl: './price-quote.component.html',
  styleUrls: ['./price-quote.component.css']
})
export class PriceQuoteComponent implements OnInit {

  //Do not connect to the stock service, use a random number generator to simulate the stock price changes, and display the stock code and the latest price stockCode: string = "IBM";
  price: number;

  @Output() //The emission event needs to be written as Output
  //EventEmitter requires a generic lastPrice: EventEmitter<PriceQuote> = new EventEmitter();
  //

  constructor() {
    setInterval(() => {
      let priceQuote: PriceQuote = new PriceQuote(this.stockCode, 100 * Math.random());
      this.price = priceQuote.lastPrice;
      //Use lastPrice to emit a value this.lastPrice.emit(priceQuote);
    }, 1000)
  }

  ngOnInit() {
  }

}
//Encapsulate a quote object to encapsulate stock price information //It is a good habit to clearly define specific data structures with classes or interfaces export class PriceQuote {
  constructor(public stockCode: string, //stock code public lastPrice: number //latest price) {
  }
}

3. Receive quotation information and display it in the parent component

The parent component template captures and handles this event through event binding.

export class AppComponent {
  stock = "";
  priceQuote: PriceQuote = new PriceQuote("", 0);

  //The type of event is the type of data emitted when the child component emits //The parent component can get priceQuoteHandler(event:PriceQuote){
    this.priceQuote=event;
  }
}

stencil

<!--By default, the event name is the name of the output attribute-->
<app-price-quote (lastPrice)="priceQuoteHandler($event)"></app-price-quote>

<div>
  This is outside the quote component<br/>
  The stock code is {{priceQuote.stockCode}},
  The stock price is {{priceQuote.lastPrice | number:"2.0-2"}}
</div>

By default, the event name is the name of the output attribute. You can change the event name by

@Output("priceChange") // Output is required to launch the event
  //EventEmitter requires a generic lastPrice: EventEmitter<PriceQuote> = new EventEmitter();

The template is also changed to

<app-price-quote (priceChange)="priceQuoteHandler($event)"></app-price-quote>

Summarize

Events are emitted through output properties, and data is carried through events. They are captured and processed through event binding in the parent component template.

If there is no parent-child relationship between two components, how to pass data in a loosely coupled way. At this time, the middleman mode needs to be used.

The above is a detailed explanation of the communication between Angular parent-child components. For more information about the communication between Angular parent-child components, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Detailed explanation of Angular dynamic components
  • Angular performance optimization: third-party components and lazy loading technology
  • Example of implementing communication between angular components
  • Detailed explanation of the method of value transfer test between angular components
  • Angular7 creates projects, components, services and uses services
  • Angular events: how to pass data between different components
  • Angularjs1.5 Example of using functions to pass values ​​outside a component
  • Detailed explanation of Angular6 study notes: master-slave components
  • Detailed explanation of the middleman mode of Angular components

<<:  The latest mysql-5.7.21 installation and configuration method

>>:  Win10 installation Linux system tutorial diagram

Recommend

Analysis of several situations where MySQL index fails

1. Best left prefix principle - If multiple colum...

MySQL data type details

Table of contents 1. Numeric Type 1.1 Classificat...

How to modify Flash SWF files in web pages

I think this is a problem that many people have en...

Nginx reverse proxy to go-fastdfs case explanation

background go-fastdfs is a distributed file syste...

Summary of @ usage in CSS (with examples and explanations)

An at-rule is a declaration that provides instruc...

Win10 configuration tomcat environment variables tutorial diagram

Before configuration, we need to do the following...

Summary of commonly used CSS encapsulation methods

1. pc-reset PC style initialization /* normalize....

Analysis and solutions to problems encountered in the use of label tags

I used the label tag when I was doing something re...

Let IE support CSS3 Media Query to achieve responsive web design

Today's screen resolutions range from as smal...

A brief talk about the diff algorithm in Vue

Table of contents Overview Virtual Dom principle ...

Some parameter descriptions of text input boxes in web design

<br />In general guestbooks, forums and othe...

Docker container time zone error issue

Table of contents background question Problem ana...

Pure CSS custom multi-line ellipsis problem (from principle to implementation)

How to display text overflow? What are your needs...

W3C Tutorial (15): W3C SMIL Activities

SMIL adds support for timing and media synchroniz...