Home

Awesome

ASP.NET Core 2.1 & Angular 7(+) Advanced Starter - PWA & Server-side prerendering (for Angular SEO)!


<br> <p align="center"> <a href="https://trilon.io" target="_blank"> <img width="500" height="auto" src="https://trilon.io/trilon-logo-clear.png" alt="Trilon.io - Angular Universal, NestJS, JavaScript Application Consulting Development and Training"> </a> </p> <h3 align="center"> Made with :heart: by <a href="https://trilon.io">Trilon.io</a></h3>

Harness the power of Angular 7+, ASP.NET Core 2.1, now with SEO !

Angular SEO in action:

<p align="center"> <img src="./docs/angular2-seo.png" alt="ASP.NET Core Angular7 SEO" title="ASP.NET Core Angular7 SEO"> </p>

Angular Universal Application Architecture

<p align="center"> <img src="./docs/architecture.png" alt="ASP.NET Core 2.1 Angular 7+ Starter" title="ASP.NET Core 2.1 Angular 7+ Starter"> </p>

What is this repo? Live Demo here: http://aspnetcore-angular2-universal.azurewebsites.net

This repository is maintained by Trilon.io and the Angular Universal team and is meant to be an advanced starter for both ASP.NET Core 2.1 using Angular 7.0+, not only for the client-side, but to be rendered on the server for instant application paints (Note: If you don't need SSR read here on how to disable it).

This is meant to be a Feature-Rich Starter application containing all of the latest technologies, best build systems available, and include many real-world examples and libraries needed in todays Single Page Applications (SPAs).

This utilizes all the latest standards, no gulp, no bower, no typings, no manually "building" anything. NPM, Webpack and .NET handle everything for you!

Join us on Gitter

Gitter chat

Table of Contents


Features:

These are just some of the features found in this starter!



Getting Started?

Visual Studio 2017

Make sure you have .NET Core 2.1 installed and/or VS2017 15.3. VS2017 will automatically install all the neccessary npm & .NET dependencies when you open the project.

Simply push F5 to start debugging !

Docker-Support: Change the startup project to docker-compose and press F5

Note: If you get any errors after this such as module not found: boot.server (or similar), open up command line and run npm run build:dev to make sure all the assets have been properly built by Webpack.

Visual Studio Code

Note: Make sure you have the C# extension & .NET Core Debugger installed.

The project comes with the configured Launch.json files to let you just push F5 to start the project.

# cd into the directory you cloned the project into
npm install && npm run build:dev && dotnet restore
# or yarn install

If you're running the project from command line with dotnet run make sure you set your environment variables to Development (otherwise things like HMR might not work).

# on Windows:
set ASPNETCORE_ENVIRONMENT=Development
# on Mac/Linux
export ASPNETCORE_ENVIRONMENT=Development 

Upcoming Features:



Deployment

Dotnet publish

Using dotnet publish, when it's finished place the generated folder onto your server and use IIS to fire everything up.

Heroku

<a href="https://dashboard.heroku.com/new?template=https://github.com/MarkPieszak/aspnetcore-angular2-universal.git"> <img src="https://www.herokucdn.com/deploy/button.svg" alt="Deploy on Heroku"> </a>

Azure

git remote add azure https://your-user-name@my-angular2-site.scm.azurewebsites.net:443/my-angular2-site.git
                     // ^ get this from Azure (Web App Overview section - Git clone url)

git push --set-upstream azure master 

Application Structure:

Note: This application has WebAPI (our REST API) setup inside the same project, but of course all of this could be abstracted out into a completely separate project('s) ideally. .NET Core things are all done in the same project for simplicity's sake.

Root level files

Here we have the usual suspects found at the root level.

Front-end oriented files:

/ClientApp/ - Everything Angular

Let's take a look at how this is structured so we can make some sense of it all!

With Angular Universal, we need to split our applicatoin logic per platform so if we look inside this folder, you'll see the 2 root files, that branch the entire logic for browser & server respectively.

Here we setup a few things, client Angular bootstrapping.

You'll barely need to touch this file, but something to note, this is the file where you would import libraries that you only want being used in the Browser. (Just know that you'd have to provide a mock implementation for the Server when doing that).


Notice the folder structure here in ./ClientApp/ :

+ /ClientApp/

+   /app/
    App NgModule - our Root NgModule (you'll insert Components/etc here most often)
    AppComponent / App Routes / global css styles

    * Notice that we have 2 dividing NgModules:
        app.module.browser & app.module.server
    You'll almost always be using the common app.module, but these 2 are used to split up platform logic
    for situations where you need to use Dependency Injection / etc, between platforms.

Note: You could use whatever folder conventions you'd like, I prefer to split up things in terms of whether they are re-usable 
     "components" or routeable / page-like components that group together and organize entire sections.
++ > ++ > /components/ 
          Here are all the regular Components that aren't "Pages" or container Components

++ > ++ > /containers/
          These are the routeable or "Page / Container" Components, sometimes known as "Dumb" Components

++ > ++ > /shared/
          Here we put all shared Services / Directives / Pipes etc

When adding new features/components/etc to your application you'll be commonly adding things to the Root NgModule (located in /ClientApp/app/app.module.ts), but why are there two other NgModules in this folder?

This is because we want to split our logic per Platform, but notice they both share the Common NgModule named app.module.ts. When adding most things to your application, this is the only place you'll have to add in your new Component / Directive / Pipe / etc. You'll only occassional need to manually add in the Platform specific things to either app.module.browser || app.module.server.

To illustrate this point with an example, you can see how we're using Dependency Injection to inject a StorageService that is different for the Browser & Server.

// For the Browser (app.module.browser)
{ provide: StorageService, useClass: BrowserStorage }

// For the Server (app.module.server)
{ provide: StorageService, useClass: ServerStorage }

Just remember, you'll usually only need to worry about app.module.ts, as that's where you'll be adding most of your applications new aspects!

/Server/ - Our REST API (WebApi) - MVC Controller

As we pointed out, these are here for simplicities sake, and realistically you may want separate projects for all your microservices / REST API projects / etc.

We're utilizing MVC within this application, but we only need & have ONE Controller, named HomeController. This is where our entire Angular application gets serialized into a String, sent to the Browser, along with all the assets it needs to then bootstrap on the client-side, and become a full-blown SPA afterwards.


The short-version is that we invoke that Node process, passing in our Request object & invoke the boot.server file, and we get back a nice object that we pass into .NETs ViewData object, and sprinkle through out our Views/Shared/_Layout.cshtml and /Views/Home/index.cshtml files!

A more detailed explanation can be found here: ng-AspnetCore-Engine Readme

// Prerender / Serialize application
var prerenderResult = await Prerenderer.RenderToString(
    /* all of our parameters / options / boot.server file / customData object goes here */
);

ViewData["SpaHtml"] = prerenderResult.Html;
ViewData["Title"] = prerenderResult.Globals["title"];
ViewData["Styles"] = prerenderResult.Globals["styles"];
ViewData["Meta"] = prerenderResult.Globals["meta"];
ViewData["Links"] = prerenderResult.Globals["links"];

return View(); // let's render the MVC View

Take a look at the _Layout.cshtml file for example, notice how we let .NET handle and inject all our SEO magic (that we extracted from Angular itself) !

<!DOCTYPE html>
<html>
    <head>
        <base href="/" />
        <!-- Title will be the one you set in your Angular application -->
        <title>@ViewData["Title"] - AspNET.Core Angular 7.0.0 (+) starter</title>

        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        @Html.Raw(ViewData["Meta"]) <!-- <meta /> tags -->
        @Html.Raw(ViewData["Links"]) <!-- <link /> tags -->
        
        <link rel="stylesheet" href="~/dist/vendor.css" asp-append-version="true" />

        @Html.Raw(ViewData["Styles"]) <!-- <style /> tags -->

    </head>
    ... etc ...

Our Views/Home/index.cshtml simply renders the application and serves the bundled webpack files in it.

@Html.Raw(ViewData["SpaHtml"])

<script src="~/dist/vendor.js" asp-append-version="true"></script>
@section scripts {
    <script src="~/dist/main-client.js" asp-append-version="true"></script>
}

What happens after the App gets server rendered?

Well now, your Client-side Angular will take over, and you'll have a fully functioning SPA. (But we gained all these great SEO benefits of being server-rendered) !

:sparkles:



"Gotchas"

When building components in Angular 7 there are a few things to keep in mind.

constructor(element: ElementRef, renderer: Renderer2) {
  this.renderer.setStyle(element.nativeElement, 'font-size', 'x-large');
}


FAQ - Also check out the !FAQ Issues label! and the !HOW-TO Issues Label!

How can I disable SSR (Server-side rendering)?

Simply comment out the logic within HomeController, and replace @Html.Raw(ViewData["SpaHtml"]) with just your applications root AppComponent tag ("app-root" in our case): <app-root></app-root>.

You could also remove any isPlatformBrowser/etc logic, and delete the boot.server, app.module.browser & app.module.server files, just make sure your boot.browser file points to app.module.

How do I have code run only in the Browser?

Check the Gotchas on how to use isPlatformBrowser().

How do I Material2 with this repo?

You'll either want to remove SSR for now, or wait as support should be coming to handle platform-server rendering. This is now possible, with the recently updated Angular Material changes. We do not have a tutorial available for this yet.

How can I use jQuery and/or some jQuery plugins with this repo?

Note: If at all possible, try to avoid using jQuery or libraries dependent on it, as there are better, more abstract ways of dealing with the DOM in Angular (5+) such as using the Renderer, etc.

Yes, of course but there are a few things you need to setup before doing this. First, make sure jQuery is included in webpack vendor file, and that you have a webpack Plugin setup for it. new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery' })

Now, make sure any "plugins" etc that you have, are only included in your boot.browser.ts file. (ie: import 'slick-carousel';) In a Component you want to use jQuery, make sure to import it near the top like so:

import * as $ from 'jquery';

Always make sure to wrap anything jQuery oriented in Angular's isPlatformBrowser() conditional!

How can I support IE9 through IE11?

To support IE9 through IE11 open the polyfills.ts file in the polyfills folder and uncomment out the 'import polyfills' as needed. ALSO - make sure that your webpack.config and webpack.config.vendor change option of TerserPlugin from ecma: 6 to ecma: 5.


Special Thanks

Many thanks go out to Steve Sanderson (@SteveSandersonMS) from Microsoft and his amazing work on JavaScriptServices and integrating the world of Node with ASP.NET Core.

Also thank you to the many Contributors !


Found a Bug? Want to Contribute?

Check out our easier issues here

Nothing's ever perfect, but please let me know by creating an issue (make sure there isn't an existing one about it already), and we'll try and work out a fix for it! If you have any good ideas, or want to contribute, feel free to either make an Issue with the Proposal, or just make a PR from your Fork.


License

MIT License

Copyright (c) 2016-2019 Mark Pieszak

Twitter Follow


Trilon - Angular & ASP.NET - Consulting | Training | Development

Check out Trilon.io for more info! Twitter @Trilon_io

Contact us at hello@trilon.io, and let's talk about your projects needs.

<p align="center"> <a href="https://trilon.io" target="_blank"> <img src="https://trilon.io/trilon-logo-clear.png" alt="Trilon.io - Angular Universal, NestJS, JavaScript Application Consulting Development and Training"> </a> </p>

Follow Trilon online:

Twitter: @Trilon_io