×

How to Create a Web Application Using ASP.NET Core 3.0 and Angular Dec 20, 2019

How to Create a Web Application Using ASP.NET Core 3.0 and Angular

If you are a web developer, creating a web application using ASP.NET Core 3.0 and Angular is a value proposition. You can use this technology stack to bring robust, performant and economical solutions to the market. 

On the other hand, businesses can get a good ROI from such applications. They can get in touch with the consultants of any good ASP.NET Core development company to explore further.

Being a Senior .Net Core Consultant of Microsoft Partnered Company, my intention of writing this article is to guide both, my community of developers as well as businesses. 

This is what you will get to know after reading this full-length article – 

  • Why .NET Core 3.0 is a preferred choice for developing web applications?
  • The real challenge developers might face when combining .NET Core and Angular.
  • A complete overview of the implementation process of Angular and ASP.NET Core applications.
  • How to create a web application using ASP.NET Core and Angular? This will be a step-by-step tutorial. 

Let’s begin.

Why .NET Core 3.0 is a Preferred Choice for Developing Web Applications?

With .NET Core 3.0, Microsoft has launched the next major version of the modular, general-purpose, cross-platform and open-source platform. The IT innovator created .NET Core to allow for the next generation of ASP.NET solutions. But now, it drives many other technological domains such as IoT, cloud, mobility, and others. Version 3 of ASP.NET Core has added a number of benefits such as support for WPF, WinForms, and Entity Framework 6.

These benefits and the added capabilities of Angular will help you develop one of the best web applications. However, you will come across one challenge before starting with the implementation process.

Challenge Faced When Combining .NET Core and Angular

You can start combining Angular and ASP.NET Core using a Visual Studio template provided by Microsoft. But here is a limitation. Angular takes control of the UI while ASP.NET Core runs in the background, thus serving as an API. 

Here is the solution for it. 

If you want to develop some pages using .NET Core and other pages using Angular, you will have to duplicate the look and feel and the menu structure in both frameworks. Alternatively, you can serve the entire UI through a single Angular app. But in the latter case, you have to implement all the pages including the static content in Angular SPA (Single Page Application).

So how do you go about the implementation? Let’s find out by reading further.

Steps to Implement the Web Application Using .NET Core 3.0 and Angular

  1. Build an ASP.NET MVC web application using .NET Core 3.0.
  2. Create an Angular project using Angular CLI and integrate that project into the ASP.NET project.
  3. Use Bootstrap in the Angular project to get the Web Components i.e. custom elements.
  4. Use Angular CLI to generate applications. These applications will get the reusable components from the root Angular project.
  5. Embed Angular apps in ASP.NET Core Views using iframes pointing to the same domain.
  6. IFrames use JavaScript to re-size with content. Then you should integrate the ASP.NET Core routing with the iframed Angular apps.
  7. Package Angular components as Web Components to host them in ASP.NET Core views. 

What We Will Achieve After Implementing the Web Application

  • An ASP.Net Core website that acts like a portal with a menu structure and each menu should open up an MVC view.
  • Host Angular SPAs within that website.
  • Reuse some of the components from those SPAs in ASP.NET views.

Now, it’s time to get started with the implementation process of the web application.

Create ASP.NET Core MVC Project

Use Visual Studio 2019 Community Edition. In this version, the wizard for choosing templates is different from previous versions, but regardless of which version you have, the steps are about the same.

  1. Go to Create a New Project and select ASP.NET Core Web Application.
  2. Choose the name and location for the project (this is MultiAppDemo) and select ASP.NET Core.
  3. Select ASP.NET Model-View-Controller. Keep things simple by selecting No Authentication. By doing so, VS will not generate artifacts irrelevant for this walk-through.

Your project view in the Solution Explorer will look like this:

Since we are using the ASP.NET Core MVC template and not the SPA template, we will have to add Microsoft.AspNetCore.SpaServices.Extensions NuGet package. To install the package, open the Package Manager Console and run the following command:

Install-Package Microsoft.AspNetCore.SpaServices.Extensions

Create an Angular Project

Before starting this step, you should have the following free software installed:

  • Visual Studio Code
  • Node.js
  • Angular CLI. To install, execute this command in the command prompt: npm install -g @angular/CLI

Preferring to the recent version, we will move with Angular version 8 for the current implementation. Using an earlier version is fine if it has access to the createCustomElement API. 

In order to create an Angular solution in the ASP.NET Core MVC project, run the command prompt and navigate to the folder containing the project file (extension .csproj) for your MVC project. Now, you can execute the following command to create the Angular project:

ng new Apps

Select N for routing and CSS for styling.

Change directory to Apps, and type the following (including the trailing period):

code.

You should now have your Angular project opened in the Visual Studio Code.

Bootstrap Angular Elements

This root project acts as a repository for reusable components that will be available to other Angular applications as normal Angular components and to the MVC views as Web Components.

Webcomponents.org defines it as: Web components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps.

Angular allows you to package Angular components as web components through an API called Angular Elements. For example, if you create an Angular component that shows the current time and bootstrap this component as an Angular element current-time, you can then include <current-time /> tag in plain HTML pages. 

In VS Code, open your Angular project. Open a terminal window and type a command to generate the clock component and to add that component to app.module.ts:  

ng g c current-time

You will get a folder called current-time under src/app with several files that build your clock component. Change app/current-time/current-time.component.html to have the following markup:

<p>{{ time }}</p>

Change your app/current-time/current-time.component.ts to have the following code:

import { Component, OnInit, OnDestroy } from ‘@angular/core’;
@Component({  selector: ‘app-current-time’,  templateUrl: ‘./current-time.component.html’,  styleUrls: [‘./current-time.component.css’]})export class CurrentTimeComponent implements OnInit, OnDestroy {  timer: any;  time: string
  constructor() { }
  ngOnInit() {    var setTime = () => {      var today = new Date();      this.time = (“0” + today.getHours()).slice(-2) + “:” +                  (“0” + today.getMinutes()).slice(-2) + “:” +                  (“0” + today.getSeconds()).slice(-2);    };    setTime();    this.timer = setInterval(setTime, 500);  }
  ngOnDestroy(){    if (this.timer){      clearTimeout(this.timer);    }  }}

The implementation is rather simple. We have a timer that fires every half a second. The timer updates the time property with a string representing the current time, and the HTML template is bound to that string.

Paste the following styles in app/current-time/current-time.component.css

p {    background-color: darkslategray;    color: lightgreen;    font-weight: bold;    display: inline-block;    padding: 7px;    border: 4px solid black;    border-radius: 5px;    font-family: monospace;}

Now, start saving all the modified files and bootstrap the clock component as a web component:

  1. Open a new terminal window inside Visual Studio Code.
  2. Add Angular Elements libraries and polyfills. To do that type the following command at the terminal window: ng add @angular/elements
  3. Navigate to src/app/app.module.ts
  4. If it’s not there already, add the following import statement at the top of app.module.ts: import { createCustomElement } from ‘@angular/elements’;
  5. Add Injector to the import from @angular/core: import { NgModule, Injector } from ‘@angular/core’;
  6. Replace bootstrap: [AppComponent] with entryComponents: [ClockComponent]
  7. Lastly, add the constructor and ngDoBootstrap to the AppModule class.
constructor(private injector: Injector) {}
ngDoBootstrap(){  customElements.define(‘current-time’, createCustomElement(CurrentTimeComponent,                                                      {injector: this.injector}));

exports: [    CurrentTimeComponent],

Your entire app.module.ts will look like this:

import { BrowserModule } from ‘@angular/platform-browser’;import { NgModule, Injector } from ‘@angular/core’;
import { AppComponent } from ‘./app.component’;import { createCustomElement } from ‘@angular/elements’;import { CurrentTimeComponent } from ‘./current-time/current-time.component’;@NgModule({  declarations: [    AppComponent,    CurrentTimeComponent  ],  imports: [    BrowserModule  ],  exports: [    CurrentTimeComponent  ],  providers: [],  entryComponents: [CurrentTimeComponent]})export class AppModule {  constructor(private injector: Injector) {  }
  ngDoBootstrap(){    customElements.define(‘current-time’, createCustomElement(CurrentTimeComponent,                                                          {injector: this.injector}));  }}

After doing this, let’s test if our solution works. Go to src\index.html and replace <app-root></app-root> with <current-time></current-time>. Type ng serve –open from the terminal window to run the project. You should now see the current time showing in your browser.

Use Web Components in ASP.NET Project

Moving further, we have to make our current-time component available in the ASP.NET MVC Core Project. To complete this step, open the ASP.NET project in Visual Studio. Paste the following code before the closing </body> tag in Views/Shares/_Layout.cshtml

<environment include=”Development”>    <script type=”text/javascript” src=”http://localhost:4200/runtime.js”></script>    <script type=”text/javascript” src=”http://localhost:4200/polyfills.js”></script>    <script type=”text/javascript” src=”http://localhost:4200/styles.js”></script>    <script type=”text/javascript” src=”http://localhost:4200/scripts.js”></script>    <script type=”text/javascript” src=”http://localhost:4200/vendor.js”></script>    <script type=”text/javascript” src=”http://localhost:4200/main.js”></script></environment><environment exclude=”Development”>    <script asp-src-include=”~/Apps/dist/core/runtime-es2015.*.js” type=”module”></script>    <script asp-src-include=”~/Apps/dist/core/polyfills-es2015.*.js” type=”module”></script>    <script asp-src-include=”~/Apps/dist/core/runtime-es5.*.js” nomodule></script>    <script asp-src-include=”~/Apps/dist/core/polyfills-es5.*.js” nomodule></script>    <script asp-src-include=”~/Apps/dist/core/scripts.*.js”></script>    <script asp-src-include=”~/Apps/dist/core/main-es2015.*.js” type=”module”></script>   <script asp-src-include=”~/Apps/dist/core/main-es5.*.js” nomodule></script></environment>

You will observe two blocks in the previous code segment. One is for development and the other one for non-development. While we are in the development phase, our Angular project that hosts web components will be running on port 4200, started from VS Code. During production, the Angular project will get compiled into wwwroot/apps/core folder with javascript files named with hashes appended. You have to use asp-src-include tag helpers in order to properly reference the files.

Next, in _Layout.cshtml, add <current-time></current-time> right after the </main> closing tag.

We need to test that our development configuration works by performing the following steps:

  • Go to VS Code where your Angular project is opened, and type this command at the terminal prompt: ng serve –liveReload=false
  • Go to Visual Studio where your ASP.NET project is opened and hit F5 to run the project.

Your ASP.NET site will now open up and you will see the current time component displayed on every page.

Create an Angular Application

Web Components work great and are the future of web UIs, but bootstrapping Angular projects as Single Page Applications (SPAs) offers more benefits.

Angular is based on the concept of modules and some of the features, such as routing, are related to modules, not components. When combining Angular and ASP.Net Core web application development, I would host Angular apps in MVC views. The ASP.NET MVC should be able to provide the top-level menu structure and the SPAs should provide their own menu and routing structure that is a part of a larger MVC application. Moreover, I want to reuse codes and share them between multiple SPAs within the solution and also include them in the non-Angular pages as web components.

The first step to achieve this is to create a new application in Angular. You should use the Angular CLI (command line interface) for this step. Start your Angular project in VS Code, followed by starting a new terminal window. At the terminal, execute this command:

ng g application App1 –routing=true

A new Angular application is generated under Apps\projects\App1 with the routing module configured. We’ll now generate two components and set up the routes. Execute from the terminal:

ng g c Page1 –project=App1

ng g c Page2 –project=App1

You can now see two new component folders, page1 and page2, under Apps/Projects/App1/src/app.

We can now set up routing for these components. Change your app.component.html under Apps/Projects/App1/src/app:

<h2>App1</h2>  <a routerLink=”/page1″ routerLinkActive=”active”>Page1</a>  <a routerLink=”/page2″ routerLinkActive=”active”>Page2</a><router-outlet></router-outlet>

And update your app-routing.module.ts under Apps/projects/App1/src/app with the following code:

import { NgModule } from ‘@angular/core’;import { Routes, RouterModule } from ‘@angular/router’;import { Page1Component } from ‘./page1/page1.component’;import { Page2Component } from ‘./page2/page2.component’;
const routes: Routes = [  {path: ”, redirectTo: ‘page1’, pathMatch: ‘full’},  {path: ‘page1’, component: Page1Component},  {path: ‘page2’, component: Page2Component}];
@NgModule({  imports: [RouterModule.forRoot(routes)],  exports: [RouterModule]})export class AppRoutingModule { }

Let’s test the configuration of our new application. Open a new terminal window and type this command:

ng serve App1 –port 4201 –open

Your browser will open and you will see something like this

We are making the use of port 4201 which is different from what we used for the root Angular project. Each app you develop will have to be served on a different port in development. But in non-development environments, all apps of ASP.NET and Angular can run on the same port.

Now, it’s time to achieve code re-use. We’ll reuse the Angular component from the base project in App1. You can do that by including an import of the CurrentTimeComponent in the App1’s main module.

Go to app.module.ts under Apps/projects/App1/src/app and add the following import statement:

import { CurrentTimeComponent } from ‘../../../../src/app/current-time/current-time.component’;

What we are doing is importing the CurrentTimeComponent from the root project. Alternatively, you can import the entire AppModule from the root project.

The next step is to add CurrentTimeComponent to the list of declarations:

  declarations: [    AppComponent,    Page1Component,    Page2Component,    CurrentTimeComponent  ],

Now, go to app.component.html in App1, and add the tag for the current time, right below the router outlet.

<h2>App1</h2><a routerLink=”/page1″ routerLinkActive=”active”>Page1</a><a routerLink=”/page2″ routerLinkActive=”active”>Page2</a><router-outlet></router-outlet><app-current-time></app-current-time>

If you have an eye for detail, you might have noticed we used the Angular tag (app-current-time) for this component, not the web component tag name (current-time). This is because we wanted to include the component as the Angular component. App1 is not aware of this Angular component used elsewhere as a web component.

Save all files and check the browser. Your App1 page should now show the current time component.

Summing it Up

So this was all for this tutorial on web application development. You can get in touch with our consultants in case of any queries or ideas. They’ll be happy to help you.

Information and image source: InfoQ article

5/5 (1)

Rate Us!