...

/

Angular Micro Front-End

Angular Micro Front-End

Learn how to render micro front-ends in Angular, and inject React and Vue apps into DOM elements with controlled visibility.

The time has come to finally put all three of our applications together as a single micro front-end application. We will be using a JavaScript technique to coordinate the display of front-ends, and in our case, we will use Angular to do this. This means that we will use our existing Angular application to set up regions within a page to inject our front-ends into.

Note: The code examples as presented here are a logical progression of concepts in building our micro front-end. If you are following along and find that something doesn’t quite work as expected, please refer to the sample code present in the last lesson of this chapter. We will be covering quite a bit of ground in terms of source code, and having a code editor open with the final version of the sample code at hand may help to understand how it all fits together.

Micro front-end DOM Containers

Our Angular application already has a header panel and a login panel that is rendered as a Material Sidenav container.

Let’s update our angular-app/src/app/app.component.html file to set up container <div> elements for our micro front-ends to be injected into as follows:

Press + to interact
<app-header></app-header>
// Existing mat-sidenav
<mat-sidenav-content>
<div class="content-padding">
<div [hidden]="hideProducts" class="split left">
<h2>Product List</h2>
<div id="root"></div>
</div>
<div [hidden]="hideShoppingCartRegion"
class="{{shoppingCartStyles}}">
<h2>Shopping Cart</h2>
<p *ngIf="hideShoppingCart">
Please login to view your shopping cart
</p>
<div [hidden]="hideShoppingCart"
id="vue-application"></div>
</div>
<div [hidden]="hideOrderPlaced" class="split left">
<h2>Order Placed</h2>
</div>
</div>
</mat-sidenav-content>
</mat-sidenav-container>
<router-outlet></router-outlet>

Here, we have updated our <mat-sidenav-content> region to include tree <div> elements, which have a [hidden] attribute that is being controlled by a component variable.

  • Lines 5–8: For the first div, if the hideProducts variable on the AppComponent class is set to true, then this <div> element will be hidden. We will be rendering the React Product List front-end into this <div> element and controlling visibility via the hideProducts member variable.
  • We also have a <div> element for our Vue front-end on lines 9–17 and another <div> element that will show when an order has been placed on lines 18–20.

Also, note that we are not using an *ngIf directive here to control the visibility of a <div> element; we are using the [hidden] property instead. The reason for this is that both React and Vue, as micro front-ends, need a specific <div> element present in the DOM in order to render their content. The *ngIf directive will actually remove the <div> element ...