Add Angular 5 CLI project to ASP.Net Core 2.0 project

  • Create a ASP.Net project by clicking Add new project->Web->ASP.NET Core Web Application. Select the following options at “New ASP.NET Core Web Application” dialog:
  • .NET Core
  • ASP.NET Core 2.0
  • Web Application (Model-View-Controller)
  • Click “Ok”
  • For example, we name the web project as ASPCoreAngular5 which located at c:\projects\ASPCoreAngular5Sln solution folder.
  • After you created your ASP.NET Core project, you need to turn off the default typescript automatic compiler from your VS2017 project file. What you need to do is to unload the project and open project in a XML editor and add the following lines in your project file.
<PropertyGroup><TargetFramework>netcoreapp2.0</TargetFramework><TypeScriptCompileBlocked>true</TypeScriptCompileBlocked><TypeScriptToolsVersion>Latest</TypeScriptToolsVersion></PropertyGroup>
  • Make sure you have latest node.js including NPM.
  • Run command.exe as administrator and go to ASPCoreAngular5 solution folder, for our sample case, it would be “c:\projects\ASPCoreAngular5Sln”.
  • Make sure you have Angular Cli installed. If you don’t, run the following command which will install Angular CLI globally:
npm install -g @angular/cli@latest
  • Enter the following command to create an Angular Cli with same folder as ASP.NET Core solution. The purpose for that is to have package.json and .angular-cli.json are located at the same level as the ASP.NET Core project folder which is one level below the solution folder. I also used — source-dir ClientApp which makes the Angular App source folder is ClientApp.
  • routing: create routing module.
  • skip-git: skip git creation
  • directory: specify the folder as ClientApp. the client side TS code will be located at ClientApp folder which is under ASPCoreAngular5 project folder.
ng new ASPCoreAngular5 —-routing --skip-git --source-dir ClientApp
  • Once the project is created, you can run ng serve to test the application. As ng server is created an in-memory files for browser use. You need to build the angular project if you want to see the actual JS files.
  • When Angular CLI build a project, it will generate all files to the one defined in .angular-cli.json file. Open up .angular-cli.json file and change the output to “../wwwroot/dist”. This will generate built files to wwwroot folder.
  • root: define the root folder, for our case, “ClientApp” will be the root of TypeScripts.
  • outDir: this is output folder. We are going to generate output files to wwwroot/dist folder which will be reference from index.cshtml.
  • styles: the style css you want to include. If you use bootstrap, you need to include bootstrap css to here.
  • scripts: the JavaScript libraries you want to include. We used bootstrap and jQuery, so that we need to bundle them. You can skip them if you want to include their CDN to index.cshtml.
“apps”: [{“root”: “ClientApp”,“outDir”: “./wwwroot/dist”,“assets”: [“assets”,“favicon.ico”],“index”: “index.html”,“main”: “main.ts”,“polyfills”: “polyfills.ts”,“test”: “test.ts”,“tsconfig”: “tsconfig.app.json”,“testTsconfig”: “tsconfig.spec.json”,“prefix”: “app”,“styles”: [“styles.css”,“../node_modules/bootstrap/scss/bootstrap.scss”],“scripts”: [“../node_modules/jquery/dist/jquery.min.js”,“../node_modules/bootstrap/dist/js/bootstrap.bundle.js”],
  • Go back to command line and make sure you are at project folder (for our case, it will be “c:\projects\ASPCoreAngular5Sln\ASPCoreAngular5”). Type the following command to build your angular solutions. The files will be generated under wwwroot/dist folder. All the libraries and css will be bundled to js files.
Ng build
  • Next, we need to change the ASP.NET Core View to add those generated JS to there. Open up your Views/home/index.cshtml and replace to the following code. <app-root> will be the angular entry point.
@{ViewData[“Title”] = “Home Page”;}<app-root></app-root>
  • Open up _layout.cshtml, removed the original Javascript references and replaced the code to the following:
  • <base href=”~/”>: tell how the base url is.
  • Scripts: reference the script files generated by Angular Cli.
<!DOCTYPE html><html><head><meta charset=”utf-8" /><meta name=”viewport” content=”width=device-width, initial-scale=1.0" /><title>@ViewData[“Title”] — ASPCoreAngular5_2</title><base href=”~/” /></head><body>@RenderBody()<script src=”~/dist/inline.bundle.js” asp-append-version=”true”></script><script src=”~/dist/polyfills.bundle.js” asp-append-version=”true”></script><script src=”~/dist/styles.bundle.js” asp-append-version=”true”></script><script src=”~/dist/vendor.bundle.js” asp-append-version=”true”></script><script src=”~/dist/main.bundle.js” asp-append-version=”true”></script>@RenderSection(“Scripts”, required: false)</body></html>
  • Until now, you should be able to run your ASP.NET Core SPA project by press F5. however, if you want to leverage Angular CLI server for debug purpose, you need to tell your ASP.NET Core application to use Angular CLI server to build your files instead of Visual Studio. The benefit for leveraging Angular CLI server is you don’t have to restart your debug project from Visual Studio. Whenever you save your TypeScript code, Angular CLI server will compile that and Visual Studio debugger is able to pick up whatever changes. In order to do that, you need to add Microsoft.AspNetCore.SpaServices.Extensions package which can be installed from nuget package management.
  • Once you have extension installed, open up startup.cs and add the following highlight part in configure() method to support Angular CLI Server and SPA URL routing:
  • SourcePath: we generated the Angular code at “ClientApp” folder and spa.UseAngularCliServer() method will be called only at development mode.
  • MapSpaFallbackRoute: tell the ASP.NET Core to route the SPA routing.
public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseBrowserLink();app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler(“/Home/Error”);}app.UseSpa(spa =>{spa.Options.SourcePath = “ClientApp”;if (env.IsDevelopment()){spa.UseAngularCliServer(npmScript: “start”);}});app.UseStaticFiles();app.UseMvc(routes =>{routes.MapRoute(name: “default”,template: “{controller=Home}/{action=Index}/{id?}”);routes.MapSpaFallbackRoute(name: “spa-fallback”,defaults: new { controller = “Home”, action = “Index” });});}
  • You can press F5 now to start your application in the browser. We are running at development mode, whenever you change your TypeScript code from Visual Studio, the backend Angular Server will recompile the code and refresh your browser.
  • If you want to generate the code whenever you compile the ASP.NET Core project for deployment, you can add NPM tasks into your pre build process under “Task Runner Explorer”. You will have Angular CLI to compile your code when you build your ASP.NET Core project.

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Resolving promises concurrently in JavaScript— The foolproof way

whenAll result

Now some basic of JavaScript is here

Simple JavaScript Logger in TypeScript Demonstrating Interfaces, Union Types and Rest Parameters

Use Case of JavaScript in the Industries

Our Serverless Blueprint: The step-by-step guide

MERN Auth with Session — Part 1: Express Login API

Header Bidding 101: Client-Side Vs Server-Side

How To Send Email With Attachment In Laravel 8

How To Send Email With Attachment In Laravel 8

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Frank Chen

Frank Chen

More from Medium

Integrate Firebase Real Time Database with  .Net

Firebase + .Net integration

Develop an Online Shop with Angular 11 and .Net Core 5

Angular Tutorial By Example: REST API, HttpClient GET, Components, Services & ngFor

Inside ASP.NET Core 6 React Template