concept mediator in category angular

appears as: Mediator, mediator, The mediator
Angular Development with Typescript, Second Edition

This is an excerpt from Manning's book Angular Development with Typescript, Second Edition.

We’ll continue with an example that applies the Mediator design pattern to arrange data exchange between components that don’t have parent-child relationships. Mediator is probably the most important design pattern in any component-based framework.

8.3.1. Using a common parent as a mediator

Let’s revisit the first figure of this chapter, shown again in figure 8.4. Each component except 1 has a parent (a container) that can play the role of mediator. The top-level mediator is container 1, which is responsible for making sure its direct children 2, 3, and 6 can communicate if need be. On the other hand, component 2 is a mediator for 4 and 5. Component 3 is a mediator for 7 and 8.

Figure 8.4. A view consists of components.

The mediator needs to receive data from one component and pass it to another. Let’s go back to examples of monitoring stock prices.

Imagine a trader monitoring the prices of several stocks. At some point, the trader clicks the Buy button next to a stock symbol to place a purchase order with the stock exchange. You can easily add a Buy button to the PriceQuoterComponent from the previous section, but this component doesn’t know how to place orders to buy stocks. PriceQuoterComponent will notify the mediator (AppComponent) that the trader wants to purchase a particular stock at that moment.

The mediator should know which component can place purchase orders and how to pass the stock symbol and quantity to it. Figure 8.5 shows how an AppComponent can mediate the communication between PriceQuoterComponent and OrderComponent.

Listing 15.9. The state of the mediator app
export interface State {
  searchQuery: string;           #1
   searchResults: string[];      #2
 }