In this post I will show how to use Angular to render server side templates.
A key win of the Angular architecture is that the framework is not tied to a particular runtime platform.
While browsers still remain the most typical platform for Angular applications, it’s easy to execute Angular code on other runtimes. One popular option is server side rendering.
In this post I will show how to use Angular Universal to render pure server side templates in Node/Express.
In my application I am less interested in the client side part.
Instead I will focus on the server side part since I want to use Angular to replace some of my existing Mustache templates.
The feature I want to convert is my Angular article dashboard.
Since all my existing server templates use Mustache, I had to find a way to allow Angular and Mustache to coexist in the same application.
The solution I ended up with was to create a sub application in Express where I configured Angular as the view engine. In the main app the view engine is still Mustache.
Below is my sub Express application:
Back in the main application I can now import the sub app and register it like so:
Now, any request to /angular-2-articles will be routed to the sub application.
Not only is this approach great for supporting multiple view engines, it also makes my application more modular.
From here on out we’re pretty much just dealing with standard Angular code.
I have included the relevant Angular code below:
You may have noticed that for server side applications we import BrowserModule.withServerTransition, but otherwise most of the code is familiar Angular code.
What I really like about this is that we can use most standard Angular functionality – even the async pipe works.
It’s also very easy to implement complex template logic since you have full access to Angular template directives like ngIf and ngFor.
You do however have to stay away from browser specific api functions (e.g. DOM functions).
I was very happy to see how easy it was to convert my existing Mustache solution to Angular server templates. You can see the final version here.
Going forward I might even convert more of my templates.