Detailed explanation of angular parent-child component communication

Time:2021-7-28
catalogue
  • summary
  • 1、 Overview of input and output properties
  • 2、 Input properties
  • 3、 Property binding is one-way, from parent component to child component
  • 4、 Output properties
    • 1. First, simulate a real-time changing IBM stock price
    • 2. Output the information and tell the external components who are interested and who will subscribe
    • 3. Receive and display quotation information in parent component
  • summary

    summary

    Communication between angular components

    In the component tree, No. 1 is the root component appcomponent.

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

    Click the button in component 4 to trigger the initialization logic of component 5.

    Traditional practice: call the method of component 5 in the click event of button 4. Tight coupling.

    Angular: implemented when component 4 does not know the existence of component 5 at all.

    Loose coupling is used to transfer data between components to develop high reusable components.

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

    1、 Overview of input and output properties

    Components are designed as black box models, with input properties declaring what they receive from the outside world. You don’t need to know where these things come from.

    The component only needs to know what it should do when the external world provides it with what it needs.

    Components emit events through output properties to tell the outside world what may be of interest. There is no need to know who the event is sent to.

    Who is interested and who subscribes to events emitted by the component.

    2、 Input properties

    The subcomponent defines two input attributes, which are decorated by 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 input attribute of the child component.

    <div>
      I am the parent component
    </div>
    <div>
      < input type = "text" [(ngmodel)] = "stock" placeholder = "please enter 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 stockcode value of the subcomponent to apple every 3S.

    
    export class OrderComponent implements OnInit {
    
      @Input()
      stockCode:string;
      @Input()
      amount:number;
    
      constructor() { 
        setInterval(()=>{
          this.stockCode='Apple'
        },3000)
      }
    
      ngOnInit() {
      }
    }

    When the stockcode value of the child component changes to apple, the stock value of the parent component does not change. Note the binding is one-way. Only the parent component can change the child component, and the change of child component properties will not affect the parent component.

    4、 Output properties

    The angular component can use the EventEmitter object to emit custom events, which can be processed by other components. EventEmitter is a subclass of the subject class in rxjs. In responsive programming, it can be either an observer or an observer. The event can be emitted through the event subscribe method, that is, the emitter method of the event subscriber.

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

    Example scenario: Quotation component

    Suppose you need a component that can be connected to the stock exchange and display the changing stock price in real time. In order to make this component reusable in different financial applications, in addition to displaying the stock price in real time, the component should also send the latest stock price to the component, In this way, other components can execute corresponding business logic for changing stock prices.

    Note: it is a good habit to explicitly define specific data structures with classes or interfaces

    1. First, simulate a real-time changing IBM stock price

    export class PriceQuoteComponent implements OnInit {
    
      //Do not connect to the stock service, use a random number generator to simulate the change of stock price, 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 quotation object to encapsulate stock price information
    //It is a good practice to explicitly 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 external components who are interested and who will subscribe

    The paradigm behind eventemit is what type of event data is to be sent out.

    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 change of stock price, and display the stock code and the latest price
    
      stockCode: string = "IBM";
      price: number;
    
      @Output() // output needs to be written when launching an event
      //EventEmitter requires a template
      lastPrice: EventEmitter<PriceQuote> = new EventEmitter();
      //
    
      constructor() {
        setInterval(() => {
          let priceQuote: PriceQuote = new PriceQuote(this.stockCode, 100 * Math.random());
          this.price = priceQuote.lastPrice;
          //Use lastprice emit to get a value
          this.lastPrice.emit(priceQuote);
        }, 1000)
      }
    
      ngOnInit() {
      }
    
    }
    //Encapsulate a quotation object to encapsulate stock price information
    //It is a good practice to explicitly define specific data structures with classes or interfaces
    export class PriceQuote {
      Constructor (public stockcode: string, // stock code
        Public lastprice: number // latest price
      ) {
      }
    }

    3. Receive and display quotation information in parent component

    The parent component template is captured and processed by event binding.

    export class AppComponent {
      stock = "";
      priceQuote: PriceQuote = new PriceQuote("", 0);
    
      //The type of event is the type of data emitted by the sub component during emit
      //The parent component can be obtained through event
      priceQuoteHandler(event:PriceQuote){
        this.priceQuote=event;
      }
    }

    Template

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

    @Output ("pricechange") // output needs to be written when launching an event
      //EventEmitter requires a template
      lastPrice: EventEmitter<PriceQuote> = new EventEmitter();

    The template is also changed to

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

    summary

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

    If there is no parent-child relationship between two components, how to transfer data in a loosely coupled way. In this case, you need to use the middleman mode.

    The above is a detailed explanation of the communication of angular parent-child components. For more information about the communication of angular parent-child components, please pay attention to other relevant articles of developeppaer!

    Recommended Today

    SQL exercise 20 – Modeling & Reporting

    This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress:https://github.com/nino-laiqiu/TiTanI recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]