Why Angular ? Angular vs jQuery


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.
And this is what the list of lessons will look like:
{
"-KgVwEC-dwWkLO4ZsQ9e": {
"description": "Angular Tutorial For Beginners - Build Your First App - Hello World Step By Step",
"longDescription": "This is step by step guide to create your first Angular application. Its aimed at beginners just starting out with the framework.This lesson will show how to create a component, and how to link the component to a given custom HTML tag. It will show how to give the component a given template.",
"tags": "BEGINNER",
"url": "angular-hello-world-write-first-application",
"videoUrl": "https://www.youtube.com/embed/du6sKwEFrhQ"
},
"-KgVwEC0vq_chg0dvlrb": {
"courseId": "-KgVwEBq5wbFnjj7O8Fp",
"description": "Building Your First Angular Component - Component Composition",
"duration": "2:07",
"longDescription": "In this lesson we are going to see how to include a component inside another component. We are going to create a simple search box component and include it in our main application.",
"tags": "BEGINNER",
"url": "angular-build-your-first-component",
"videoUrl": "https://www.youtube.com/embed/VES1eTNxi1s"
}
....
}

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.
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.
<div class="container">
<div id="lessons"></div>
</div>

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<script src="./index.js"></script>

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:
$(document).ready(function() {
$.get( "https://final-project-recording.firebaseio.com/lessons.json",
function( data ) {
var lessons = Object.values(data);
console.log(lessons);
...
}
);
});

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:
<!-- View 1 - A table with a list of lessons -->
<table class="table lessons-list">
<thead>
<tr>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Angular Tutorial For Beginners - Build Your First App - Hello World Step By Step</td>
</tr>
<tr>
<td>Building Your First Angular Component - Component Composition</td>
</tr>
</tbody>
</table>


<!-- View 2 - An aggregated view of the data -->
<div>31 lessons</div>

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:
$.get( "https://final-project-recording.firebaseio.com/lessons.json",
function( data ) {
var lessons = Object.values(data);

var html = "<table class='table lessons-list'>' + " +
"'<thead>" +
"<th>Description</th>" +
"</thead>" +
"<tbody>";

lessons.forEach(function(lesson) {
html += '<tr>' + +
'<td>' + lesson.description + '</td>' +
'</tr>';
});

html += '</tbody></table>';

$("#lessons").html(html);

}
);

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:
@Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
lessons: any[];
constructor(private http:Http) {}
ngOnInit() {
this.http.get('https://final-project-recording.firebaseio.com/lessons.json')
.map(res => Object.values(res.json()))
.subscribe(lessons => this.lessons = lessons);
}
}

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:
<table class='table lessons-list'>
<thead>
<th>Description</th>
</thead>
<tbody>
<tr *ngFor="let lesson of lessons">
<td>{{lesson.description}}</td>
</tr>
</tbody>
</table>
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.

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.

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!

HAPPY CODINGđź’“

Comments