Note: This post is part of the ongoing Angular for Beginners series, here is the complete series:
-
Angular For Beginners Guide - Getting Started (Setup Environment)
-
Why a Single Page Application, What are the Benefits? What is a SPA?
Why Angular?
When setting up your initial Angular development environment using the Angular CLI, you will realize how much the CLI has now become essential.
This is because we need so much more setup today when compared to what we had before - and this is the case not only for Angular but also for any other equivalent ecosystem.
A couple of key questions
In this new world of module loaders, advanced build systems that we no longer set up ourselves from scratch, and where everything is transpiled down to plain ES5 Javascript from higher level languages, it would not be surprising if at a given point you would ask yourself:
Do I really need all these tools and dependencies? Isn't there a simpler way, what is the advantage of doing thing this way? Why Angular?
You might even ask yourself, why not do everything in a previously existing technology, like jQuery for example?
There are many use cases that are still today well solved by that approach, but that lead us to the question:
In which way does Angular improve upon previously existing technologies?
What problems does Angular solve in a fundamentally better way, and why is it better?
Everything happens under the hood
Let's find out! The key thing about the main advantages of Angular and MVC is that everything happens so much under the hood that it's sometimes hard to realize that the advantages are even there.
In order to understand the benefits of the MVC approach, we are going to build a small application in for example jQuery, and then build its equivalent in Angular - and the differences between both will quickly become apparent.
The goal here is not to compare Angular with jQuery, but to compare the MVC approach to frontend development with pre-MVC approaches.
jQuery is used here because it's a very well known example, and it's still very useful today for many use cases.
An example of a jQuery Application
To understand the advantages that both Angular and MVC bring, let's give a simple example. Let's start with a simple application that just displays a list of lessons on the screen.
The lessons will be loaded via an HTTP GET request from this url. Actually, this data is coming from Firebase via its alternative HTTP API (learn more about it in the Firebase Crash Course).
And this is what the list of lessons will look like:
What is the Model in MVC?
As we can see, the data above is simply a Plain Old Javascript Object or POJO.
Those unique identifiers that you see are Firebase push keys, more on them on the Angular and Firebase Crash Course.
The JSON object above is the data of our application, also known as the Model, and we would like to display it on the screen - therefore we need to generate HTML based on this Model.
So let's start by doing so in jQuery first, and then implement the same logic in Angular.
What does a jQuery application look like?
Lets build a small jQuery application to display this data (the application is available here):
So in our jQuery application, the first thing that we need to do is to query our REST API backend by doing a jQuery Ajax request:
Notice that we called Object.values()
, this was so just to transform the returned result which was an object (and therefore a key-value dictionary) into a list of lessons.
Note: the order of the lessons is not guaranteed to be preserved
With this we now have our Model in the browser, ready to be displayed - the list of lessons. As you can see, we did not send HTML over the wire from the server back to the client, instead, we did a request to the server and returned only the data.
This is a critical notion because the HTML is more than the data: the HTML is a particular representation of the Model, that we can call a View, and the same data could have multiple views.
The Model vs View Distinction
The same Model (the list of lessons) that we have shown above, could have multiple Views. Here are a few examples:
As we can see, one View of the model is an HTML table, but another possible View could simply be the total number of lessons.
Also, each lesson itself can be used as a Model, itself with different views: we could have a lesson detail screen showing all the detail of a lesson, of just a row in a table - showing a summary of the lesson.
How to Display the View using jQuery?
We now have the data on the frontend, so we need to use it to create the multiple Views. Here is how we could generate an HTML table with a list of lessons in jQuery:
Reviewing the jQuery application
As we can see, we are writing quite some code to take the model, and transform it into the multiple views of the data. We can see that this code although straightforward to write, has the following characteristics:
- This code is not very readable, its mixing several concerns
- this type of code is not very maintainable
- this is a lot of code, it makes for a significant portion of our application!
- we are building HTML by string concatenation and then passing it on to the browser, which will still have to parse it
This last point is important for the comparison in terms of performance, more on this later.
Enter Angular, how is it different?
So now let's rewrite this part of our application in Angular (the application can be found here).
This is only the key part of the application, there would be an Angular CLI folder structure around it, but its standard and generated for us. The Angular equivalent would then be the following:
So let's break this down and compare it to the jQuery version:
- we have here a class that knows both about the data retrieved from the backend and the HTML template needed to render it
- the HTTP request is being made via the Angular HTTP module
- the data is stored in a variable called
lessons
But the biggest apparent different is that there is no trace of HTML in this code.
The Angular View Generation Process
So how is the HTML being generated then ? Let's have a look at the app.component.html
HTML template file:
As we can see, this is where the HTML is kept now. And it's separated from the component code as it sits in a separate file altogether.
Notice that this template does have some expressions and syntax that does not look like the HTML that we write every day, such as for example:
- the
ngFor
directive that loops through the list of lessons - the
{{lesson.description}}
expression, which is how we can output data to the view
These expressions are how Angular ties the data and the view together.
The MVC Terminology
Based on the Angular application above, lets then define some terms:
- the plain JSON object is the Model of our Application
- the template (or the output of its processing) is the View
- the Angular
AppComponent
binds the View and the Model together
Angular vs jQuery - comparing the two versions of the application
Now that we have two applications written in both jQuery and Angular, let's start comparing them.
Already in this initial stage, we can see several differences:
- the template of Angular is much more readable than the jQuery code
- the
AppComponent
code does not generate HTML, it only fetches the data from the backend
The biggest difference just looking at the code is that in the Angular version there is a separation of concerns that does not exist on the jQuery version.
In the Angular version, the Model and the View are clearly separated and interact via the AppComponent
class, while in the jQuery version all of these concerns are mixed in the same code.
But that is not the only advantage of using an MVC framework: the differences will become much more apparent if we start modifying the data.
What if we now Modify the Model?
The separation of concerns of the Angular version is a great thing to have, and essential in a larger application.
But there is more going on in this small example that is not yet apparent: what if we now want to update the Model? Let's say that now we want to change the title of each lesson, to include the sequential number of the lesson.
To make it simple, let's do this in response to a button. This is what the jQuery version would look like:
So let's break it down what is going on in this new version of the code:
- we have extracted the code to generate the HTML into a separate function called
generateHtml()
, so that we can reuse it (see the function below) - we have stored the lessons data inside a module so that it does not pollute the global scope
- we have added a click handler to a button, that modifies the data and then calls again the
generateHtml()
function
The function that we created for reusing the HTML generation logic looks like the following:
The problem with this type of code
It might not look like it, but this code is really fragile and hard to maintain: one single quote in the wrong place and we will still have a valid Javascript string that will look completely broken when rendered by the browser, as it's not valid HTML.
This is the type of code that we don't want to have to write ourselves: it's really brittle, even though it might look straightforward at a first glance.
Comparing with the Angular version
Now let's have a look at the equivalent Angular version of this code:
The updateCourses
function is being called by a button that we added to the template:
Reviewing the Angular data modification version
Like its jQuery counterpart, this version of the application is also adding an index to the description of each course (have a look at these ngFor features for an alternative).
What we did in this Angular version was: we simply updated the Model, and Angular has automatically reflected the Model modification directly in the View for us!
We did not have to call an HTML generation function, apply the HTML in the right place of the document, etc. This is one of the killer features of Angular:
we did not have to write any Model to View Synchronization code manually, that synchronization has been somehow done for us under the hood!
So how does this work?
Angular keeps the View in sync with the model for us at all times via its transparent change detection mechanism.
The way that this works is that Angular will automatically check the Model, to see if it has changed and if so it will reflect those changes in the view.
But besides the separation of concerns and the automated detection of changes and synchronization, there is something else fundamentally different between the jQuery and the Angular versions.
Maybe The Biggest Difference Between Angular and jQuery?
We cannot tell just by looking at the Angular code because it all happens transparently, but one of the key differences is that unlike jQuery, Angular is doing the document modification in a much more efficient way than the jQuery version:
Angular is not generating HTML and then passing it to the browser to have it parsed, instead Angular is generating DOM data structures directly!
This works much faster than building manually HTML and then passing it to the DOM for parsing. By building DOM nodes directly, Angular is bypassing the HTML parsing step altogether. So the browser simply takes the ready to use DOM tree and renders it to the screen.
And more than that, it will do so in an optimal way, by trying to change just the HTML that absolutely needs to be changed:
Angular will not replace the whole DOM tree each time, it updates the DOM in an optimal way, depending on what parts of the Model have changed
How is Angular rendering the View under the hood?
In order to understand better what Angular is doing under the hood, let's do the following: let's go back to the jQuery version and try to do something similar to what Angular is doing - direct DOM manipulation.
The click handler code would now look something like this:
So as we can see we are using directly the DOM API to remove the nodes under the lessons
Div. Then we are replacing the table with a new table that was created using the generateDomTable()
function.
And this is what that function looks like:
If you would like to see this in action, clone and try locally the two sample applications (one application in Angular and the other in jQuery).
The Advantages of the Angular View Generation Process
Actually, this is just a very rough approximation of what Angular is doing under the hood.
This function is regenerating the whole table, but what Angular does with its templates is that it will replace only the parts of the DOM tree that need to be modified, according to only the data that was modified.
So for example, if only an expression on the page title was modified, that is the only part of the DOM that will be affected, the list of lessons would remain unchanged.
It's just not practical to do manually what Angular is doing
And this is where it would become almost impossible and certainly impractical to do with jQuery the same thing that Angular is doing transparently under the hood.
Its simply not practical to write this type of Model to View DOM generation code manually ourselves like the generateDomTable()
, despite the benefits of that approach.
For example, notice that the generateDomTable()
function although it creates DOM nodes directly, it's not optimized and generates the whole table each time.
Summary and Conclusions
So let's summarize: the advantages of using an MVC framework like Angular as we have seen are huge, so let's list them one by one.
Separation Of Concerns
We can build frontend applications with a lot less code than previous generation technologies. This is because we don't have to write code that manually synchronizes the Model and the View - that code is generated for us automatically.
The code that we do need to write will be a lot more readable and maintainable, due to the clear separation of concerns between the Model and the View.
Transparent Model to View Synchronization
The synchronization between Model and View is not only transparent but its optimized in a way that is not possible in practice to achieve manually.
UI Performance
The View is modified by generating directly DOM object trees in a cross-browser compatible way, instead of by generating HTML and then passing it to the browser for parsing - this effectively bypasses the parsing step altogether.
The HTML still needs to be parsed, but it's done only once per template by Angular and by the browser each time. The parsing is done either at application startup time (Just In Time, or JIT), or ahead of time (AOT) when be build the application.
And this one of the main reasons why it's so worth to have a more advanced development environment like the CLI: because using it we can have all these features and benefits working transparently out of the box.
Also, the generation and modification of the view are itself done in an optimized way, meaning that only the parts of the DOM tree that have modified data will be affected, while the rest of the page remains the same.
Why MVC has become essential for frontend development
With Angular and MVC we can focus on building applications in a more declarative way, by simply defining an HTML template just like we are used to.
We can them bind the template to the Model data, and handle the data via a component class.
Is it doable not to use MVC ?
Choosing to not use an MVC framework means that we will have to keep the Model and the View in sync manually, which looks simple at first sight but very quickly we will end up with an unmaintainable program.
I hope that this gives you a convincing explanation about why we need an MVC framework like Angular, and this type of technology solves for us a large number of problems in a completely transparent way.
And why it really pays off to setup a more advanced working environment, to be able to enjoy all these benefits and great developer experience.
I hope that this post helped understand what are some of the key benefits of using a framework like Angular, and that you enjoyed it!
This post is part of the ongoing Angular for Beginners series, here is the complete series:
-
Angular For Beginners Guide - Getting Started (Setup Environment)
-
Why a Single Page Application, What are the Benefits? What is a SPA?
I invite you to subscribe to our newsletter to get notified when more posts like this come out:
If you are just getting started learning Angular, have a look at the Angular for Beginners Course:
Other posts on Angular
Have also a look also at other popular posts that you might find interesting:
- Getting Started With Angular - Development Environment Best Practices With Yarn, the Angular CLI, Setup an IDE
- Why a Single Page Application, What are the Benefits ? What is a SPA ?
- Angular Smart Components vs Presentation Components: What's the Difference, When to Use Each and Why?
- Angular Router - How To Build a Navigation Menu with Bootstrap 4 and Nested Routes
- Angular Router - Extended Guided Tour, Avoid Common Pitfalls
- Angular Components - The Fundamentals
- How to build Angular apps using Observable Data Services - Pitfalls to avoid
- Introduction to Angular Forms - Template Driven vs Model Driven
- Angular ngFor - Learn all Features including trackBy, why is it not only for Arrays ?
- Angular Universal In Practice - How to build SEO Friendly Single Page Apps with Angular
- How does Angular Change Detection Really Work ?