Click here to Skip to main content
15,885,366 members
Articles / Web Development

Building an Angular 13 Application with .NET 6 (Global Market) - Part 1

Rate me:
Please Sign up or sign in to vote.
5.00/5 (18 votes)
19 May 2022CPOL7 min read 49.9K   904   55   13
Build a simple finance application with Angular 13 and .NET 6
This article shows how to create an Angular 13 frontend and .NET 6 backend from VS 2022, and introduces some Angular fundamentals like multiple projects workspace, Angular library, and development proxy.

Image 1

Introduction

In this article, I show you how to create an Angular 13 frontend and .NET 6 backend from Visual Studio 2022, and also introduce some Angular fundamentals, like multiple projects workspace, Angular library, and development proxy.

Create ASP.NET Core App with Angular in Visual Studio 2022

Visual Studio 2022 introduced a new JavaScript and TypeScript experience. There are three standalone project templates, standalone Angular, standalone React, and standalone Vue. These templates use each framework’s native CLIs to create these front-end project. In this article, we only talk about Angular.

Prerequisites

  • Visual Studio 2022 (17.1 or above). In earlier version of Visual Studio 2022, there was a bug to create Angular 13 (latest version). So please make sure your Visual Studio 2022 is up to date.
  • Angular CLI

    Install Node.js 16 or above.

    Then install the latest Angular CLI.

    Shell
    npm install -g @angular/cli

    This command will install Angular 13.3 (the latest version).

Create the Angular App

Start Visual Studio 2022, select “Standalone TypeScript Angular Project”.

Image 2

When you get to the Additional information windows, check the Add integration for Empty ASP.NET Web API Project option. This option adds files to your Angular template so that it can be hooked up later with the ASP.NET Core project.

Image 3

Select this option, proxy will be setup once the project is created.

aspnetcore-https.js, proxy.conf.js.

Image 4

And config proxy in angular.json.

JSON
"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "configurations": {
    "production": {
      "browserTarget": "GlobalMarket:build:production"
    },
    "development": {
      "browserTarget": "GlobalMarket:build:development"
    }
  },
  "defaultConfiguration": "development",
  "options": {
    "proxyConfig": "src/proxy.conf.js"
  }
}

Create Web API Project

In the same solution, add ASP.NET Core Web API project.

Image 5

Name this backend project as “GlobalMarket API”.

Image 6

Right click GlobalMarketAPI project and choose Properties. Go to the Debug menu and select Open debug launch profiles UI option.

Image 7

Uncheck the Launch Browser option.

Image 8

Set the Startup Project

Right-click the solution and select Set Startup Project. Change the startup project from Single startup project to Multiple startup projects. Select Start for each project’s action.

Image 9

Next, select the backend project and move it above the frontend, so that it starts up first.

Image 10

Change Angular Proxy Setting

Check APP URL in GlobalMarketAPI launch profiles UI.

Image 11

Then, go to the proxy.conf.js file for your Angular project (look in the src folder). Update the target property to match the applicationUrl.

JavaScript
const PROXY_CONFIG = [
  {
    context: [
      "/weatherforecast",
    ],
    target: "https://localhost:7219",
    secure: false
  }
]

module.exports = PROXY_CONFIG;

Now start the solution by press “F5” or click “Start” button at the top menu.

Image 12

Angular Workspace

Currently, the frontend is single Angular project. Visual Studio 2022 standalone Angular project using ng new to create Angular application. By default, ng new creates an initial skeleton application at the root level of the workspace, along with its end-to-end tests. The skeleton is for a simple Welcome application that is ready to run and easy to modify. The root-level application has the same name as the workspace, and the source files reside in the src/ subfolder of the workspace. This simple structure is fine for beginners.

In this article, I make it a little bit complicated, which is creating multiple projects and libraries in single workspace.

Right click “GlobalMarket” project in solution explorer, select “Open Terminal”.

Image 13

It will open a PowerShell terminal window under GloblaMarket folder.

Image 14

Create a “trading” Angular project in GlobalMarket workspace.

Shell
ng generate application trading --style=css --routing=false

This command create files for application in the sub-folders projects/trading:

  • tsconfig.*.ts files. They extend the workspace root tsconfig.ts and set specific configuration to compile the application (tsconfig.app.ts) or its unit tests (tsconfig.spec.ts).
  • The src folder, it contains all TypeScript, HTML and CSS sources for your application (More on the src folder structure).
  • The karma.conf.js Karma configuration file used for unit tests.

Now we need merge the files created by Visual Studio 2022 Standalone Angular template to the new trading project.

Copy all files in GlobalMarket\src\ to GlobalMarket\projects\trading\src\. Then delete GlobalMarket\src folder.

Edit GlobalMarket\angular.json. Add proxy configuration to “serve” section of ‘trading” project.

JSON
"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "configurations": {
    "production": {
      "browserTarget": "trading:build:production"
    },
    "development": {
      "browserTarget": "trading:build:development"
    }
  },
  "defaultConfiguration": "development",
  "options": {
    "proxyConfig": "projects/trading/proxy.conf.js"
  }
},

Remove the original GlobalMarket project from projects. Then change “defaultProject” to “trading”.

XML
"defaultProject": "trading"

Save changes in angular.json. Now the solution file structure should look like the below:

Image 15

Click “Start” button or press “F5” to check if everything is OK.

Image 16

This is exactly same as before, which verifies the multiple projects architecture working fine.

Trading View Widget

What we talked so far is the foundation of the solution, .NET 6, Angular 13 and how they work together.

From now, we start to talk about how to build a simple finance application. TradingView is a charting platform used by traders and investors worldwide.

TradingView widget is a free widget can be used in Ract, Angular and Vue. There is a angular-tradingview-widget is already built in github (https://github.com/mostafizur044/angular-tradingview-widget). Let’s try to install it first.

Right click “GlobalMarket” project and Open in Terminal. Run the below command:

PowerShell
npm install --save angular-tradingview-widget

Image 17

Install failed, because angular-tradingview-widget is using Angular 9, not supporting Angular 13 yet.

Don’t worry. We can use the source files in github repository to build our own tradingview-widget Angular 13 library.

Angular Library

An Angular library is an Angular project that differs from an application in that it cannot run on its own. A library must be imported and used in an application. Libraries extend Angular's base functionality.

Now we create tradingview-widget library in GlobalMarket workspace.

PowerShell
ng generate library tradingview-widget

The ng generate command creates the projects/tradingview-widget folder in GlobalMarket workspace, which contains a component and a service inside an NgModule.

When generating a new library, the workspace configuration file, angular.json, is updated with a project of type library.

JSON
"projects": {
  ...
  " tradingview-widget": {
    "root": "projects/my-lib",
    "sourceRoot": "projects/my-lib/src",
    "projectType": "library",
    "prefix": "lib",
    "architect": {
      "build": {
        "builder": "@angular-devkit/build-angular:ng-packagr",
        ...

Solution Explorer looks like the below:

Image 18

You can see that there is a file under tradingview-widget\src called “public-api.ts”. What it is?

To make library code reusable, you must define a public API for it. This "user layer" defines what is available to consumers of your library. A user of your library should be able to access public functionality (such as NgModules, service providers and general utility functions) through a single import path.

The public API for your library is maintained in the public-api.ts file in your library folder. Anything exported from this file is made public when your library is imported into an application. Use an NgModule to expose services and components.

TypeScript
/*
 * Public API Surface of tradingview-widget
 */

export * from './lib/tradingview-widget.service';
export * from './lib/tradingview-widget.component';
export * from './lib/tradingview-widget.module';

Now just copy tradingview-widget.components.ts. tradingview-widget.model.ts and tradingview-widget.module.ts from https://github.com/mostafizur044/angular-tradingview-widget/tree/main/projects/angular-tradingview-widget/src/lib to GlobalMartket\porjects\tradingview-widget\srec\lib.

Add the below code to public-api.ts.

PowerShell
export * from './lib/tradingview-widget.model';

Let’s build tradingview-widget library in command line. Still go to PowerShell terminal.

PowerShell
ng build tradingview-widget

Image 19

There are a few build errors with Angular 13, most is type error. Let’s fix it.

  • Property ‘_widegtConfig’ has no initializer and is not definitely assigned in the constructor.

    Add the initializer in tradingview-widget.component.ts:

    TypeScript
    private _widgetConfig: ITradingViewWidget = {};

    Still looks not right, it complains ‘symbol’ is missing in type {}.

    Declare ‘symbol’ of ITradingViewWidget interface is nullable in tradingview-widget.model.ts.

    TypeScript
    symbol?: string;
  • widgetType Type ‘undefined’ cannot be used as an index type.

    Add null-suppression operator “!

    TypeScript
    new TradingView[widgetType!](config);
  • Parameter ‘onload’ implicitly has an ‘any’ type.

    Declare ‘onload’ as ‘any’.

    TypeScript
    appendScript(onload : any) {
  • updateOnloadListener Object is possibly ‘null’.

    Change updataOnloadListener as the below:

    TypeScript
    updateOnloadListener(onload: any) {
        const script = this.getScriptElement();
        const oldOnload: any = script!.onload!.bind(script!);
        return script!.onload = () => {
          oldOnload();
          onload();
        };
    };

    Build again. Now it succeeds.

Image 20

You can publish your library.

Go to GlobalMarket\dist\tradingview-widget folder. You can see package files are created. Run “npm publish” to publish the library.

PowerShell
npm publish

If you only use your own library in your applications, you don’t have to publish your library to the npm package manager. You only need build it.

Use TradingView-Widget Library in Application

We have built tradingview-widget library, now use it in trading application.

Import the library by name in app.module.ts.

TypeScript
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { TradingviewWidgetModule } from 'tradingview-widget'

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
    TradingviewWidgetModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Import ITradingViewWidget and Themes from tradingview-widget library, then declare widgetConfig in app.component.ts.

TypeScript
import { Component } from '@angular/core';
import { ITradingViewWidget, Themes } from 'tradingview-widget'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  widgetConfig: ITradingViewWidget = {
    symbol: 'MSFT',
    widgetType: 'widget',
    allow_symbol_change: true,
    height: 540,
    width: 980,
    hideideas: true,
    hide_legend: false,
    hide_side_toolbar: true,
    hide_top_toolbar: false,
    theme: Themes.LIGHT,
  };

  constructor() {
  
  }

  title = 'GlobalMarket';
}

Finally update app.comonent.html.

HTML
<tradingview-widget [widgetConfig]="widgetConfig"></tradingview-widget>

Now run it, working like a charm.

Image 21

TradingView widget has a lot of built-in functionalities. You can change the symbol to whatever you interested.

For example, we can change the symbol from Microsoft to Bit Coin.

Click symbol field.

Image 22

In symbol search dialog, type “BitCoin”. Then select “BTCUSD” symbol.

Image 23

Now the chart is switched to bitcoin chart.

Image 24

If you worried about the price of petrol, have a look crude oil futures.

Select NYMEX Crude Oil Futures July 2022.

Image 25

Displays the crude oil futures chart.

Image 26

How to Use the Source Code

Download and extract source code, open GlobalMaket.sln with Visual Studio 2022.

Then right click GlobalMarket project in Solution Explorer, select “Open in Terminal”.

Need build tradingview-widget library first.

Shell
npm install

ng build tradingview-widget

Then click “Start” button or press “F5”. It should start both GlobalMarket and GlobalMarketAPI projects, and bring the trading view in your default browser.

Conclusion

In this article, we started from Visual Studio 2022 Standalone Angular template, then built a tradingview-widget library, at last, we used this library in trading app.

In part 2, we'll continue to build this finance app, calling Yahoo Finance API at backend and enhance the frontend with Angular Material.

History

  • 11th April, 2022: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Australia Australia
Fred is a senior software developer who lives in Melbourne, Australia. In 1993, he started Programming using Visual C++, Visual Basic, Java, and Oracle Developer Tools. From 2003, He started with .Net using C#, and then expertise .Net development.

Fred is often working with software projects in different business domains based on different Microsoft Technologies like SQL-Server, C#, VC++, ASP.NET, ASP.Net MVC, WCF,WPF, Silverlight, .Net Core and Angular, although he also did some development works on IBM AS400.

Comments and Discussions

 
QuestionNice tutorial. Now one could use Angular with AspNetCore API Preview Pin
Alan Wei 202311-Jun-23 11:26
Alan Wei 202311-Jun-23 11:26 
QuestionMy Regards Pin
Jacob Moss31-May-22 8:19
professionalJacob Moss31-May-22 8:19 
QuestionCompile problems Pin
eLdsTorP Solutions28-May-22 13:03
eLdsTorP Solutions28-May-22 13:03 
AnswerRe: Compile problems Pin
Fred Song (Melbourne)29-May-22 1:56
mvaFred Song (Melbourne)29-May-22 1:56 
QuestionTypo when trying to create trading project Pin
GoTexans19-May-22 7:46
GoTexans19-May-22 7:46 
AnswerRe: Typo when trying to create trading project Pin
Fred Song (Melbourne)19-May-22 13:26
mvaFred Song (Melbourne)19-May-22 13:26 
GeneralMy vote of 5 Pin
tNealB17-May-22 10:20
tNealB17-May-22 10:20 
GeneralMy vote of 5 Pin
tNealB17-May-22 10:19
tNealB17-May-22 10:19 
Questioncomment Pin
Maria1594913-May-22 20:13
Maria1594913-May-22 20:13 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA12-May-22 19:20
professionalȘtefan-Mihai MOGA12-May-22 19:20 
QuestionCreate the Angular App .. images Pin
Serg Levin15-Apr-22 4:59
professionalSerg Levin15-Apr-22 4:59 
AnswerRe: Create the Angular App .. images Pin
Fred Song (Melbourne)16-Apr-22 19:39
mvaFred Song (Melbourne)16-Apr-22 19:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.