The Core Question: Why Angular?
Once you have your Angular development environment configured with the Angular CLI, it becomes clear how indispensable the CLI has become.
Modern development demands far more setup than it once did, and this holds true not only for Angular but for virtually every comparable ecosystem.
Fundamental Questions to Consider
In an era dominated by module loaders, sophisticated build systems that are generated rather than hand-crafted, and where high-level languages are transpiled down to plain ES5 JavaScript, you may find yourself questioning the complexity:
Is all this tooling and these dependencies truly necessary? Isn't there a simpler path? What is the actual benefit of this approach? Why Angular?
You might even consider sticking with established technologies like jQuery for everything.
While jQuery still effectively addresses many use cases, this raises a crucial point:
How does Angular represent a genuine improvement over these earlier technologies?
Which problems does Angular solve more effectively, and what makes its approach superior?
The Hidden Nature of Angular's Advantages
Let's explore this. The primary benefits of Angular and the MVC pattern are so deeply integrated into the framework that they operate invisibly, making it challenging to recognize they exist at all.
To truly appreciate the MVC benefits, we will construct a simple application using jQuery and then build its Angular counterpart. The differences between the two will become immediately obvious.
The objective is not to pit Angular against jQuery directly, but rather to contrast MVC-based frontend development with pre-MVC methodologies.
jQuery serves as a well-understood benchmark and remains highly relevant for numerous scenarios today.
A Simple jQuery Application Example
To illustrate the benefits of Angular and MVC, let's consider a basic application that simply renders a list of lessons.
The lesson data is fetched via an HTTP GET request from this url. This data is hosted on Firebase and accessed through its alternative HTTP API (see the Firebase Crash Course for more details).
Here is a preview of what the lesson list will look like:
Defining the Model in MVC
Observe that the data is just a Plain Old JavaScript Object, or POJO.
The unique identifiers you see are Firebase push keys, which are discussed in more depth in the Angular and Firebase Crash Course.
This JSON object constitutes the data of our application, known as the Model. Our goal is to display it, which means we need to generate HTML based on this Model.
Let's first implement this in jQuery, and then we will replicate the functionality in Angular.
The Anatomy of a jQuery Application
Let's create a simple jQuery application to render this data (the full application is available here):
The first step in our jQuery application involves querying the REST API backend with a jQuery Ajax request:
We use Object.values() to convert the response, which is an object (or key-value dictionary), into an array of lessons.
Note: the sequence of the lessons is not ensured
Now we have our Model loaded in the browser, ready for display. As you can see, we did not receive HTML from the server; instead, we requested and received only the data.
This distinction is vital because HTML represents more than just data: it is one specific rendering of the Model, known as a View, and the same data can be associated with multiple Views.
The Model vs View Distinction
The same Model (the lesson list) shown above could be represented by several different Views. Consider these examples:
One View of the Model is an HTML table, while another could simply be a count of the total lessons.
Furthermore, an individual lesson can be treated as a Model with its own set of Views: we could have a detailed lesson detail screen or a concise table row that provides a summary.
Rendering the View with jQuery
Now that we have the data on the client side, we need to use it to construct the various Views. Here's how we could generate an HTML table listing lessons in jQuery:
Evaluating the jQuery Application
As you can see, writing the code that transforms the Model into its various Views requires quite a bit of effort. While straightforward to build, this code exhibits several traits:
- it is not very readable and mixes multiple concerns
- it is not easily maintainable
- it represents a substantial amount of code and forms a major part of the application
- it constructs HTML via string concatenation and passes it to the browser, which then must parse it
This final point is critical for our performance comparison, a topic we will revisit.
Introducing Angular: Key Differences
Now, let's implement this part of the application in Angular (the application can be found here).
This is just the core part of the application. A standard Angular CLI folder structure would surround this, but it is generated for us. The Angular equivalent would appear as follows:
Let's break this down and compare it to the jQuery version:
- we define a class that is aware of both the data retrieved from the backend and the HTML template required to display it
- the HTTP request is issued using the Angular HTTP module
- the retrieved data is held in a variable named
lessons
However, the most noticeable difference is that there is no HTML within this code.
The Angular View Generation Process
So, how is the HTML generated in this case? Let's examine the app.component.html template file:
This is where the HTML now resides. It is kept isolated from the component class, sitting in a separate file.
Note that this template includes expressions and syntax that differ from regular HTML, such as:
- the
ngFordirective, which iterates over the lessons list - the
{{lesson.description}}expression, used to output data into the view
These expressions are used by Angular to link the data and the view together.
MVC Terminology
Based on the Angular application above, let's establish some definitions:
- the plain JSON object serves as the Model of our application
- the template (or its processed output) constitutes the View
- the Angular
AppComponentacts as the bridge binding the View and the Model
Angular vs jQuery: Comparing the Two Versions
Now that we have both applications, one in jQuery and one in Angular, let's begin a comparative analysis.
Even at this initial stage, several distinctions emerge:
- the Angular template is significantly more readable than the jQuery code
- the
AppComponent's code is not responsible for generating HTML; its sole focus is fetching data from the backend
The most significant code-level difference is that the Angular version practices a separation of concerns that is absent in the jQuery version.
In the Angular application, the Model and the View are distinctly separated, communicating through the AppComponent class. In contrast, the jQuery version intermingles all these responsibilities in one block of code.
This is not the only advantage offered by an MVC framework: the benefits become even more pronounced when we begin altering the data.
What if the Model Changes?
The separation of concerns evident in the Angular version is excellent and becomes essential in any substantial application.
However, there is something else happening in this small example that is not yet clear: what happens if we want to update the Model? Suppose we want to modify the title of each lesson to include its sequential number.
For simplicity, let's trigger this change with a button click. Here is what the jQuery version would look like:
Let's dissect what is happening in this revised code:
- we extracted the HTML generation logic into a dedicated function,
generateHtml(), to enable its reuse (see the function below) - we placed the lessons data inside a module to avoid polluting the global scope
- we attached a click handler to a button that modifies the data and then invokes
generateHtml()again
The function we created for reusing the HTML generation logic looks like this:
The Fragility of this Approach
This code might appear simple, but it is actually quite brittle and difficult to maintain: a single misplaced quotation mark could result in a valid JavaScript string that produces completely broken HTML in the browser.
This is precisely the type of code we should avoid writing, as it is very fragile, even if it looks straightforward at first.
Comparison with the Angular Version
Now, let's examine the corresponding Angular version:
The updateCourses function is triggered by a button we added to the template:
Reviewing the Angular Data Modification Version
Like its jQuery equivalent, this version of the application also appends an index to the description of each course (see ngFor features for an alternative approach).
What we accomplished in the Angular version was: we simply updated the Model, and Angular automatically reflected that Model change in the View for us.
There was no need to call an HTML generation function or to apply the HTML in the correct location of the document. This is one of Angular's most compelling benefits:
we did not have to write any manual Model-to-View synchronization code; that synchronization was handled automatically behind the scenes.
How Does This Work?
Angular continuously maintains View-Model synchronization through its transparent change detection system.
Angular automatically checks the Model for changes, and if any are detected, it updates the View accordingly.
However, beyond the separation of concerns and automatic change detection, there is another fundamental distinction between the jQuery and Angular versions.
Potentially the Most Significant Difference Between Angular and jQuery?
We cannot discern this simply by looking at the Angular code because it happens invisibly, but one of the key differences is that Angular modifies the document far more efficiently than the jQuery version:
Angular is not generating HTML strings and handing them to the browser for parsing; instead, it constructs DOM data structures directly.
This approach is much faster than building HTML manually and then having the DOM parse it. By creating DOM nodes directly, Angular sidesteps the HTML parsing step entirely. The browser simply receives the ready-to-use DOM tree and renders it.
Furthermore, Angular does this in an optimal way, attempting to change only the HTML that absolutely requires modification:
Angular avoids replacing the entire DOM tree with each update; it updates the DOM selectively, based on which parts of the Model have changed.
How Angular Renders the View Internally
To get a clearer picture of what Angular is doing internally, let's revisit the jQuery version and try to emulate Angular's approach—direct DOM manipulation.
The click handler would now look like this:
As shown, we are using the DOM API directly to remove the nodes under the lessons Div. We then replace the table with a new one created by the generateDomTable() function.
Here is what that function looks like:
If you want to see this in action, clone and run the two sample applications locally (one in Angular, one in jQuery).
The Advantages of Angular's View Generation Process
It's important to note that this is merely a rough approximation of what Angular does under the hood.
This function regenerates the entire table. In contrast, Angular's template engine replaces only the specific parts of the DOM tree that correspond to the data that has undergone changes.
For instance, if only an expression in the page title was modified, only that part of the DOM would be affected, leaving the list of lessons untouched.
Manual Implementation is Impractical
This is where it becomes virtually impossible—and certainly impractical—to replicate with jQuery what Angular does so effortlessly behind the scenes.
Writing this kind of Model-to-View DOM generation code manually, like the generateDomTable() function, is simply not a practical endeavor, despite the potential benefits.
For example, notice that the generateDomTable() function, although it creates DOM nodes directly, is not optimized and rebuilds the entire table on every invocation.
Summary and Conclusions
Let's wrap up by reviewing the benefits of adopting an MVC framework such as Angular. The advantages are considerable, so let's go through them systematically.
Separation Of Concerns
Building frontend applications with this approach requires significantly less code than older technologies. The reason is that we no longer need to manually write the logic that keeps the Model and the View in sync—that code is produced automatically on our behalf.
The code we do write tends to be far more readable and easier to maintain, thanks to the distinct separation of responsibilities between the Model and the View.
Transparent Model to View Synchronization
The synchronization process between the Model and the View is not just automatic; it is also fine-tuned in a manner that would be nearly impossible to replicate by hand.
UI Performance
Views are updated by directly creating DOM object trees in a way that works across browsers, rather than by constructing HTML strings and handing them off to the browser for parsing. This effectively skips the parsing step during updates.
HTML still has to be parsed, but that occurs only once per template, handled by both Angular and the browser. This parsing takes place either when the application launches, known as Just In Time (JIT) compilation, or beforehand during the build process, which is called Ahead Of Time (AOT) compilation.
This is a key reason why investing in a more sophisticated development environment like the Angular CLI is worthwhile: it provides all these capabilities and benefits seamlessly without extra configuration on our part.
Furthermore, the process of generating and updating the view is itself optimized. Only the sections of the DOM tree that hold changed data are touched, while the rest of the page is left untouched.
Why MVC has become essential for frontend development
With Angular and the MVC pattern, we can build applications in a more declarative style. We simply define an HTML template in the usual way, bind that template to the Model data, and manage the data through a component class.
Is it doable not to use MVC ?
Opting out of an MVC framework means taking on the tedious task of manually keeping the Model and the View aligned. This may seem straightforward at first, but it quickly spirals into a codebase that is hard to manage and maintain.
Hopefully, this gives you a clear understanding of why an MVC framework like Angular is necessary, and how this kind of technology resolves a wide array of challenges for us transparently.
It also shows why setting up a more robust development environment is a worthwhile investment, as it unlocks all these benefits and a smooth developer experience.
I trust this post has clarified some of the main advantages of using a framework like Angular, and I hope you found it useful.
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?
You're welcome to subscribe to our newsletter to get notified when more posts like this come out:
If you are just getting started with Angular, check out the Angular for Beginners Course:
Other posts on Angular
Feel free to look over other popular posts that might be of interest:
- 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 ?
