Angular and MVC Core Architecture together in a nutshell: a real world example part 1.

jean pierre Deffo Fotso
Nov 1 · 17 min read

In the series of post, we are going to describe angular and microsoft asp.net MVC core architecture, and how their can work together . In the first part, we will go in depht inside angular architecture and specially explain what is angular component and how you can use it to build a great frontend solution (in another post we will describe other angular artifact like service, directive, pipe, routing and so on..), in the second part, we will build the full angular side part of our project, we will see how to combine angular component tree to make our application,, the third part will be dedicated to asp.net MVC core 3 architecture, especially the middleware functionality so that we can see how angular is bootstrap in asp.net core pipline and how to use dotnet core entity framework to talk to our db and serve data to angular frontend side (dotnet core is a great topic and we cannot cover in this series all asp.net of MVC problematic), in the last part of this series, we will see how to use mongodb to host our data, and then we will containerized our wall solution in docker container and deploy it in microsoft azure PAAS solution like : Azure app service (inside docker swarm, or using docker compose), azure container instance, and azure kubernetes service.

The application we will be building it’s a simulation of azure monitoring solution where we will build a custom dashboard to manage our data center, the front end will use angular framework, while the backend will be base on asp.net MVC core 3 as you can see from the image bellow:

What do you need to follow and complete this post ?

For those who want to just follow the angular side of this series, just install angular artifact because in the first par we will build a full version of the project only with angular client side technology, but if you want to follow all post in this serie, just go ahead and install all the tool in the following lines.

  1. The .NET Core tools and runtime: The .NET Core Software Development Kit includes the runtime and development tools needed to start the development project and perform database operations : download it from here, after the installation, fire a windows command line and run the following command
dotnet --version

from the commad bellow, if the installation go well, you get the version of dotnet core framework install on your machine

2. The nodejs runtime: Node.js is a runtime for server-side JavaScript applications and has become a popular platform for
development tools. In this post, Node.js is used by the Angular build tools to compile and prepare the code that ASP.NET Core MVC will send to the browser. To install it, download and run the executable from here

After the installation of nodejs runtime, from a command line run the following command

node --version  or node -v

3. Git version control: we will use git version control to the DevOps feature of this post, so go ahead and download git version control from here. As before, just fire the following command to check if git was successfull install.

git --version

This command prints out the version of the installed Git package as in the image bellow.

4. Visual studio : for developers coming from .net community, visual studio is the development environment of choice, It offers a full-featured development experience, but it can be resource hungry. Consider using Visual Studio Code, described in the next section, if you want a lighter-weight development experience, but it can also be use to just for angular fontend development as well, so go ahead and download visual studio 2019 community edition from here , Run the installer and ensure that the “ASP.NET and web development” workload is selected as you can see in the image bellow

5. Visual Studio Code: Visual Studio Code is a light-weight editor that doesn’t have all the features of the full Visual Studio product; however, it works across platforms and is perfectly capable of handling ASP.NET Core and Angular development and can I’ll use it in in this tutorial. Download and install visual studio code from here

6. Sql server local DB: make sure to also install sql sever localdb, as we will use it for the Entity framework integration part, you can download it from here

I supposed you have already have docker install in your local machine, if not so check this post, or this post

what is Angular ?

Angular is a modern web application platform that promises to provide developers with a comprehensive set of tools and capabilities to build large, robust applications. The core value proposition of Angular is to make it possible to build applications that work for nearly any platform — whether mobile, web, or desktop. The Angular team has focused on building much more than a robust application framework;they’ve also built an entire ecosystem. So angular it’s not just a framework as VUEJS or REACT ,nor it’s a simple library as REACT or other javascript library, but it’s a complete platform because it’s coming with many development tool and can be use to target many type of application. In this post we will not discuss about advantage and disadvantage of angular, nor the angular VS React VS VUE comparison because there are many topics in the web for this subject, and I’ll suppose if you are here to read this post, it because you have chosen to use angular as your frontend technology development.

As describe above, to begin angular developement we need to install angular tools, I hope you are following this post from the beginning and you have already install nodejs because to install angular tools we need nodejs packet management (NPM), so open a command line and run the command bellow:

npm install --global @angular/cli@8.1.2

The command above will install the Angular CLI (often just referred to as the CLI) is the official toolchain for building Angular applications that provide these features and more. This post use the CLI for all examples, and you’re encouraged to use it for your projects as well. You could roll your own build tooling, but that’s suggested only if the CLI doesn’t meet your needs (I’m using angular version 8.1.2)

ng -v

Fire the command above to check if angular cli tool was successfull install, you’ll get the image bellow (ng is the angular cli command)

The CLI has a number of features that aid in the development of Angular apps. Here are the primary features:

Generates new project scaffolding — Instead of having to create a new project from an existing project or creating all the files yourself, the CLI will generate a full project with a basic app already started for you.
Generates new application pieces — Need a new component? Easy; it can generate the files for you. It can generate components, services, routes, and pipes, and it also will automatically ensure they are fully wired up in the build process.
Manages the entire build toolchain — Because files need to be processed before being served to the client (such as TypeScript compilation), the CLI will process your source files and build them into an optimized version for development or production.
Serves a localhost development server — The CLI handles the build flow and then starts a server listening on localhost so you can see the results, with a live reload feature.

Incorporates code linting and formatting code — Helps enforce quality code by using the CLI to lint your code for style and semantic errors, and it can also help format your code automatically to the style rules.
Supports running unit and e2e tests — Tests are vital, so the CLI sets up Karma for running your unit tests and works with Protractor to execute your e2e tests. It will automatically pick up and execute new tests as they’re generated.

To see the full list of features, run the command bellow:

ng help

you can also read more from the angular cli online documentation here

Angular Component architecture

In many ways, a component is a way to create custom HTML elements in your
application. Many modern applications have adopted a component-based approach to developing applications. The intention is to design each piece of your application in a standalone manner that limits the amount of coupling and duplication across various parts of the program. Components are so central to how Angular applications are structured that
almost every feature is somehow linked to them. It’s impossible to make an Angular application without a component, after all. This means being able to harness the capabilities of components is vital to any angular developer,

A component includes a template, which is the HTML markup used to describe its visual layout and behavior. A component also creates a view, which is the rendered result of a component that the user can interact with and is comprised of rendering the component template. Templates may include references to other components, which will trigger them to also
be rendered as part of the rendering of the parent component.

let’s focus a minute to the application we are building in this post to see how we organised our frontend side angular project base of component architecture.

As we can see from the image, angular is just a huge tree of component which comunicated together to make an angular application. The comunication it’s base on angular engine change detection, and all component can be isolate and incapsulated base of “shadow dom”.

Angular project creation step by step

Run the following command to create the skeleton of our project (the command bellow will be run in a single line):

ng new AzureDataCenterMonitoring --directory AzureDataCenterMonitoring/ClientApp --routing true --style css
--skip-tests true --skip-git true

The ng command is provided by the @angular/cli package, and ng new creates a new Angular project. The project is named AzureDataCenterMonitoring, and the — directory argument specifies the location of the project files. The name of the ClientApp folder is conventionally used when using a web application framework in an
ASP.NET Core MVC project. The — routing and — style arguments configure the project to use URL routing for navigation and regular CSS files for styling HTML elements. The — skipTests and — skipGit arguments create a project
without unit tests and without a Git source code setup (we will integrated git in the next post). During the installation process, you may see messages telling you that optional dependencies have been skipped. This is normal and can be ignored. When the setup is complete, the result is a folder called
AzureDataCenterMonitoring/ClientApp that contains the tools and configuration files for an Angular project, along with some placeholder code to help jump-start development and check that the development tools are working.

Now, you can open the project in visual studio code by writing the following command

code .

this will open visual studio code with our generated project as in this image:

If you are using Visual Studio, choose the Open a Local Folder option when Visual Studio starts (or select File ➤ Open ➤ Folder when Visual Studio is already running) and select the AzureDataCenterMonitoring folder.

You can run the project now by firing the command bellow (before you have to navigate inside the clientApp directory from command line, you can also do it directly inside visual studio code by open a terminal command from menu Terminal ➤ new Terminal):

ng  serve --port 5200 -o
or just run
npm start

The command tell angular to build the application and run it in a local http server in port 5200, this will open a browser with the page bellow:

The structure of the generated project is explain bellow

How angular toolchain work ?

There are three important tools used in Angular development. The first tool is the TypeScript compiler, which is responsible for compiling the TypeScript code into JavaScript that can be executed by the web browser.

The second tool is webpack. The TypeScript compiler produces a JavaScript file for each TypeScript source file that it compiles. This isn’t a convenient way to distribute web applications because each file would have to be requested by the browser, leading to a series of HTTP requests for small code files. Instead,
individual JavaScript files are combined into bundles that allow the application to be delivered to the browser over fewer HTTP requests. The bundles in an Angular project are created by webpack, which is the
most popular bundler for web application development, regardless of the framework that is used (webpack is also used in React and Vue.js development, for example). The output from the npm start or ng serve command shows the bundles that webpack creates for the example project (you can see it from visual studio code image above). These are
the bundles that all Angular applications will contain:

main.js This bundle contains the application’s code and content.

polyfills.js This bundle contains code that provides support for modern JavaScript features in older browsers. The contents of this bundle are configured using the ClientApp/src/polyfills.ts file.

runtime.js This bundle includes the JavaScript code required to load and unpack the other bundle files.

styles.js The bundler includes the application’s CSS stylesheets in this bundle, expressed as JavaScript strings. The bundle also includes JavaScript code that processes the encoded strings and uses the browser’s CSS API to add the styles to the HTML document.

vendor.js This bundle contains the Angular runtime, which is responsible for processing the contents of the main.js bundle and presenting the application to the user.

The third important tool in Angular development is the Webpack Development Server (WDS), which provides an HTTP server that delivers the application to the browser. During development, the bundles delivered to the browser contain extra JavaScript code that opens a connection back to the server and awaits a signal. When a change to the project files is detected, the TypeScript compiler is used to compile the code, a new set of bundles is created, and the signal is sent to the browser to trigger a reload, ensuring that the effect of changes is immediately reflected. The image bellow show the complete toolchain:

Angular Component life cycle

Components have a lifecycle that begins with their initial instantiation, and continues with their rendering until they’re destroyed and removed from the application.
Before we can understand the lifecycle, we should look more closely at what goes into a component. The composition of components is important to master over time to create more complex and efficient Angular applications.
Components have several distinct parts that are combined to create the resulting UI

Open the file src/app/app.component.ts as in the image bellow

When we generate a component with the CLI, it creates a set of files that contain assets that are combined during rendering. Here’s a list of the primary things that compose a component:

Component Metadata Decorator — All components must be annotated with the @Component() decorator to properly register the component with Angular. The metadata contains numerous properties to help modify the way the component behaves or is rendered.

Controller — The controller is the class that is decorated with @Component(), and it contains all the properties and methods for the component. Most of the logic exists in the controller.

Template — A component isn’t a component without a template. The markup for a component defines the layout and content of the UI that a user can see, and the rendered version of the template will look at the values from the controller to bind any data.

You can just see that angular follow the MVC (Model View Controller) pattern, or as some people usually say it’s can also be view as a MVVM(Model View ViewModel) pattern.

These three pieces must exist for any component to be valid. Additionally, there are some optional capabilities that can ride alongside components to enhance them in certain situations. The first two are concepts that inject values into the component, and the rest are concepts that modify the resulting component behavior, appearance, or interaction with other components:

  • Providers and hosts — Services can be injected directly into a component if they’re not already provided at the root module level. You also have some control over how these services are discovered and where they are made available.
  • Inputs — Components can accept data being passed to them using the component inputs, which make it possible for a parent component to bind data directly into a child component, which is a way to pass data down the component tree.
  • Styles and encapsulation — Optionally, components can include a set of CSS styles that are meant to apply only to the component. This provides a layer of encapsulation for the design of components, because component styles don’t have to be injected globally. Components can configure the way that styles are injected andencapsulated into the application.
  • Animations — Angular provides an animation library that makes it easy to style component transitions and animations that plug into the template, and can define keyframes or animation states to toggle between.
  • Outputs — Outputs are properties that are linked to events that can be used to listen for data changes or other events that a parent component might be interested in, and can also be used to share data up the component tree.
  • Lifecycle hooks — During the rendering and lifecycle of a component, you can use various hooks to trigger application logic to execute. For example, you can run initialization logic once during the instantiation of the component and tear down logic during the destruction. You can also use these hooks to bring data into the component, so lifecycle hooks work well with both inputs and outputs.

you can follow see the full documentation of angular component here.

Components have a lifecycle from creation to removal, and understanding that flow will help you design quality components. There can be slight variances in how a component’s lifecycle behaves depending on the build tooling used, but in most cases that tooling will be the Angular CLI.

the image bellow describe the angular component life cycle:

The first major action is that a component is registered with the App module. This usually happens because we declare a component as part of the NgModule metadata and occurs during application bootstrap, but components could also be registered dynamically on the fly later while the application is running (see the following image from visual studio code where in app.module.ts the app.component is bootstrap as is the unique and single component generate by the angular cli tool).

When the component is registered, it creates a component factory class and stores it for later use. Then, during the application lifecycle, something will request the component. This is typically because the component was found in a template and the compiler needs the component, but sometimes components are also requested manually. At this point, an instance of the component needs to be loaded. There is a registry of components
that belong to the module, and Angular will look up the component in question and retrieve its component factory, which is generated during the compilation using the CLI before the app is run. This special class knows how to instantiate a new instance of the component. As the component is instantiated, the metadata is read and the constructor method is fired. Any construction logic will run early in the component’s life, and you should
be careful not to put anything that might depend on child components being available, because the template won’t have been parsed yet.

The component metadata will then be fully processed by Angular, including the parsing of the component template, styles, and bindings. If the template contains any child components, those will kick off the same lifecycle for those components as well, but they won’t block this component from continuing to render.

At this point, we’ve initialized the component, and a cycle begins where the child components become fully rendered, application state changes, and components are updated. During this cycle, lifecycle hooks will fire to alert you to important times when you’ll know it’s safe to do certain actions. For example, there’s a lifecycle hook that lets you know when any of the inputs have changed; another lets you know when all the child components have fully resolved (in case you have logic that depends on them to run).

At some point, the component may no longer be needed in the application. At that point, Angular will destroy the component (and all of its children). Any new instances will need to be recreated from the component factory class, as we saw earlier.

During the application rendering process and reaction to user inputs, various hooks can be used to run code at various checkpoints. These hooks are useful when you need to know that certain conditions are true before executing the code, such as ensuring that child components have been initialized, or when changes are detected.

Angular will only run a lifecycle hook if it’s defined in the component. Lifecycle hooks aren’t like event listeners — they’re special methods with specific names that are called during the component’s lifecycle if they’re defined.

The following it’s angular lifecycle hook:

OnChanges : Fires any time the input bindings have changed. It will give you an object (SimpleChange) that includes the current and previous values so you can inspect what’s changed. This is most useful to readchanges in binding values.

OnInit : This runs once after the component has fully initialized (though not
necessarily when all child components are ready), which is after the
first OnChanges hook. This is the best place to do any initialization
code, such as loading data from APIs.

OnDestroy: Before a component is completely removed, the OnDestroy hook
allows you to run some logic. This is most useful if you need to stop
listening for incoming data or clear a timer.

DoCheck: Any time that change detection runs to determine whether the application needs to be updated, the DoCheck lifecycle hook lets you imple-
ment your own type of change detection.

AfterContentInit: When any content children have been fully initialized, this hook will allow you to do any initial work necessary to finish setting up the content children components, such as if you need to verify whether con-
tent passed in was valid or not.

AfterContentChecked: Every time that Angular checks the content children, this can run so you can implement additional change detection logic.

AfterViewInit:This hook lets you run logic after all View Children have been initially rendered. This lets you know when the whole component tree has fully initialized and can be manipulated.

AfterViewChecked:When Angular checks the component view and any View Children have been checked, you can implement additional logic to determine
whether changes occurred.

The OnInit, OnChanges, and OnDestroy hooks are the most commonly used lifecycle hooks. The DoCheck, AfterContentChecked, and AfterViewChecked hooks are most useful to keep track of logic that needs to run during any change detection process, and respond if necessary. The OnInit, AfterContentInit, and AfterViewInit hooks are primarily useful to run logic during the component’s initial rendering to set it up, and each one ensures a different level of component integrity (such as it’s ready or if the
child components are also ready).

we have come to the end with this first part of angular and Asp.net MVC core post, in the second part, we will build the complete angular side project and explain how combine components (component tree) to build the whole project. Just share, share and share.

jean pierre Deffo Fotso

Written by

I’m an IT software architect and engineer loving new approach and technology

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade