Angular is one of the most popular JavaScript frameworks developed and maintained by Google. It is an open-source front-end web framework based on TypeScript. It is most suited for developing enterprise web applications because its code is reusable and maintainable.
Angular integrates some powerful features like declarative templates, end to end tooling, dependency injection and various other best practices that smoothens the development path.
The main purpose of using Angular is to create fast, dynamic and scalable web applications. We can create these applications very easily with Angular using components and directives.
Angular was started as a SPA (Single-Page-Application) framework, and now it supports dynamic content based on different users through dependency injection. It provides a platform for easy development of web-based applications and empowers the front end developers in curating cross-platform applications. YouTubeTV is the most popular example that uses Angular.
Let's compare the features of AngularJS and Angular in a tabular form:
A list of differences between AngularJS and Angular-
Feature | AngularJS | Angular |
---|---|---|
Version | AngularJS was the very first version initially released in 2010. It was a browser-side JavaScript used within HTML code and created a revolution in web application development. It is popularly known as AngularJS. | The later Angular versions were a complete rewrite of AngularJS. For example, Angular 2 was initially released in 2016. There is nothing common between Angular2 and AngularJS except the core developer's team. After that, Angular 6, Angular 7, Angular 8, Angular 9, and Angular 10 were released that are very similar to each other. These later versions are known as Angular. |
Architecture | AngularJS supports the MVC design model. | Angular uses components and directives. |
Supported Language | The recommended and supported language of AngularJS is JavaScript. | The recommended and supported language of Angular is TypeScript. |
Expression Syntax | In AngularJS, a specific ng directive is required for the image/property and an event. | Angular uses () for event binding and [] for property binding. |
Mobile Support | AngularJS doesn't provide any mobile support. | Angular provides mobile support. |
Dependency Injection | There is no concept of Dependency Injection in AngularJS. | Angular supports hierarchical Dependency Injection with uni-directional tree-based change detection. |
Routing | In AngularJS, $routeprovider.when() is used for routing configs. | In Angular, @RouteConfig{(?)} is used for the routing config. |
Structure | It is the first and basic version, so it is very easy to manage. | It has a very simplified structure that makes the development and maintenance of large applications very easy. |
Speed | It is slower because of its limited features. | It is faster than AngularJS because of its upgraded features. |
Support | It doesn't provide support or new updates anymore. | It provides active support, and frequent new updates are made. |
Following is the list of the biggest advantages of using the Angular framework:
In Angular, templates contain Angular-specific elements and attributes. These are written with HTML and combined with information coming from the model and controller, which are further rendered to provide the user's dynamic view.
In Angular, annotations are the "only" metadata set of the class using the Reflect Metadata library. They are used to create an "annotation" array. On the other hand, decorators are the design patterns used for separating decoration or modification of a class without actually altering the original source code.
Before the introduction of Angular, web developers used VanillaJS and jQuery to develop dynamic websites. Later, when the websites became more complex with added features and functionality, it was hard for them to maintain the code. Along with this, there were no provisions of data handling facilities across the views by jQuery. The need for a client-side framework like Angular was obvious that can make life easier for the developers by handling separation of concerns and dividing code into smaller bits of information (components).
Client-side frameworks like Angular facilitate developers to develop advanced web applications like Single-Page-Application. These applications can also be developed using VanillaJS, but the development process becomes slower by doing so.
Due to the following features, Angular is preferred over other frameworks:
Extraordinary Built-in Features: Angular provides several out of the box built-in features like routing, state management, RxJS library, Dependency Injection, HTTP services, etc. That's why the developers do not need to look for the above-stated features separately.
Declarative UI: Angular has declarative UI. It uses HTML to render the UI of an application as it is a declarative language. It is much easier to use than JavaScript.
Long-term Google Support: Angular is developed and maintained by Google. Google has a long term plan to stick with Angular and provide support.
When the Angular components are created, they enter their lifecycle and remain when they are destroyed. Angular Lifecycle hooks are used to check the phases and trigger changes at specific phases during the entire duration.
ngOnChanges( ): This method is called when one or more input properties of the component are changed. The hook receives a SimpleChanges object containing the previous and current values of the property.
ngOnInit( ): This is the second lifecycle hook. It is called once, after the ngOnChanges hook. It is used to initialize the component and sets the input properties of the component.
ngDoCheck( ): This hook is called after ngOnChanges and ngOnInit and is used to detect and act on changes that Angular cannot detect. In this hook, we can implement our change detection algorithm.
ngAfterContentInit( ): This hook is called after the first ngDoCheck hook. This hook responds after the content gets projected inside the component.
ngAfterContentChecked( ): This hook is called after ngAfterContentInit and every subsequent ngDoCheck. It responds after the projected content is checked.
ngAfterViewInit( ): This hook is called after a component's view or initializing a child component's view.
ngAfterViewChecked( ): This hook is called after ngAfterViewInit. It responds after the component's view or when the child component's view is checked.
ngOnDestroy( ): This hook is called just before Angular destroys the component. This is used to clean up the code and detach event handlers.
In the above hooks we have described, the ngOnInit hook is the most often used hook. Let's see how to use the ngOnInit hook. If you have to process a lot of data during component creation, it's better to do it inside the ngOnInit hook rather than the constructor
In Angular, AOT stands for Ahead-Of-Time compiler. It is used to convert your Angular HTML and TypeScript code into efficient JavaScript code during the build phase before the browser downloads and runs that code. By compiling the application during the build process provides a faster rendering in the browser.
An Angular application is made of several components and their HTML templates. Because of these Angular components and templates, the browsers are not able to understand them directly. So, Angular applications require a compilation process before they run in a browser. That's why AOT compilers are required.
Following are the advantages of using the AOT compiler in Angular:
The rendering is faster: When we use the AOT compiler, the browser gets a pre-compiled version of the application to download. Here, the browser loads executable code to render the application immediately, without waiting to compile the app first.
The Angular framework's download size is smaller: AOT facilitates you not to download the Angular compiler if the app is already compiled. The compiler is roughly half of Angular itself, so omitting it dramatically reduces the application payload.
Fewer asynchronous requests: The compiler is used to inline external HTML templates and CSS style sheets within the application JavaScript so, it eliminates separate AJAX requests for those source files.
Detect template errors earlier: While using the AOT compiler, developers can easily detect and report template binding errors during the build step before users can see them.
Better security: AOT provides better security because it compiles HTML templates and components into JavaScript files before they are served to the client. Because there are no templates to read and no risky client-side HTML or JavaScript evaluation, so the chances for injection attacks are very rare.
In Angular, JIT stands for Just-in-Time compiler. The JIT compiler provides a dynamic translation or run-time compilation, which provides a way of executing computer code that involves compilation during the execution of a program at run time rather than before execution.
Following are the main differences between JIT and AOT compiler in Angular:
Angular provides the $scope objects into a hierarchy that is typically used by views. This is called the scope hierarchy in Angular. It has a root scope that can further contain one or several scopes called child scopes.
In a scope hierarchy, each view has its own $scope. Hence, the variables set by a view's view controller will remain hidden to other view controllers.
Following is the typical representation of a Scope Hierarchy:
Following are the main building blocks of an Angular application. You can see them in the following picture:
In Angular, as soon as we make a promise, the execution takes place, but this is not the case with observables because they are lazy. It means nothing happens until a subscription is made.
Promise | Observable |
---|---|
It emits a single value. | It emits multiple values over a period of time. |
Not Lazy | Lazy. An observable is not called until we subscribe to the observable. |
We can not cancel it. |
We can cancel it by using the unsubscribe() method. |
Observable provides operators like map, forEach, filter, reduce, retry, retryWhen etc. |
Let's understand it by an example:
When you run the above Observable, you can see the following messages displayed in the following order:
Here, you can see that observables are lazy. Observable runs only when someone subscribes to them. That's why the message "Before subscribing an Observable" is displayed ahead of the message inside the observable.
Now see the example of a Promise:
When you run the above Promise, you will see the messages displayed in the following order:
Here, you can see that the message inside Promise is displayed first. This means that the Promise runs first, and then the method is called.
The next difference between them is that Promises are always asynchronous; even when the Promise is immediately resolved. On the other hand, an Observable can be both synchronous and asynchronous.
In the case of the above example, observable is synchronous. Let's see the case where an observable can be asynchronous:
When you run the above observable, you will see the messages in the following order:
A directive is a class in Angular that is declared with a @Directive decorator. Every directive has its own behavior, and you can import them into various components of an application.
Before Angular was introduced, the web developers used VanillaJS and jQuery to develop dynamic websites, but the biggest drawback of these technologies is that as the logic of the website grew, the code became more and more complex to maintain. For websites and applications that use complex logic, developers had to put in extra effort to maintain the separation of concerns for the app. Also, jQuery did not provide facilities for data handling across views.
The client-side frameworks like Angular were introduced to overcome the above problems. It provides developers many benefits over VanilaJS and jQuery by providing a new feature called components for handling separation of concerns and dividing code into smaller bits of information.
Client-side frameworks such as Angular facilitate developers to develop advanced web applications like Single-Page-Applications. So, the main reasons behind introducing Angular were to create fast, dynamic, and scalable web applications easily.
Angular CLI is a short form for Angular Command Line Interface. It is a command-line interface to scaffold and build angular apps using node.js style modules.
To use Angular CLI, we have to install it by using the following npm command:
Following is a list of some useful commands which would be very helpful while creating angular projects:
Lazy loading is one of the most powerful and useful concepts of Angular Routing. It makes the web pages easy to download by downloading them in chunks instead of downloading everything in a big bundle. Lazy loading facilitates asynchronously loading the feature module for routing whenever required using the property loadChildren.
See the following example where we are going to load both Employee and Order feature modules lazily.
See the example:
Angular Router is a mechanism that facilitates users to navigate from one view to the next as users perform application tasks. It follows the concept model of browser's application navigation.
The Angular Router, representing a particular component view for a given URL, is not part of Angular Core. It is available in a library named @angular/router, and we have to import the required router components. This process is called router imports.
See the following example of how we can import them in the app module:
A RouterOutlet is a directive from the router library that acts as a placeholder. It marks the spot in the template where the Router should display the components for that outlet. Router outlet is used as a component.
Syntax:
On the other hand, a RouterLink is a directive on the anchor tags that gives the router control over those elements. Since the navigation paths are fixed, you can assign string values to router-link directive as below,
Syntax:
During each navigation, the Router emits navigation events through the Router.events property. It allows us to track the lifecycle of the route.
Following is the list of different router events in sequence:
The RouterLinkActive is a directive used to toggle CSS classes for active RouterLink bindings based on the current RouterState. i.e., the Router will add CSS classes when this link is active and remove them when the link is inactive.
For example, you can add them to RouterLinks as follows:
The RouterState is a tree of activated routes. Every node in this tree knows about the "consumed" URL segments, the extracted parameters, and the resolved data. We can access the current RouterState from anywhere in the application by using the Router service and the routerState property.
Most front-end applications use either XMLHttpRequest interface or the fetch() API to communicate with backend services over HTTP protocol. For the same purpose, Angular provides a simplified client HTTP API known as HttpClient. This is based on top of XMLHttpRequest interface. This HttpClient is available in the @angular/common/http package, which you can import in your root module as follows:
Following are some of the crucial advantages of HttpClient:
Yes, it is possible to make an Angular application to render on the server-side. Angular provides a technology called Angular Universal that can be used to render applications on the server-side.
The crucial advantages of using Angular Universal are as follows:
Error is when the request fails on the server or fails to reach the server due to network issues. In this condition, HttpClient returns an error object instead of a successful response. To resolve this issue, we must handle the component by passing the error object as a second callback to the subscribe() method.
See the following example to understand how we handle in the component:
You can write an error message to give the user some meaningful feedback instead of displaying the raw error object returned from HttpClient.
Angular bootstrapping is nothing but to allow developers to initialize or start the Angular application. Angular supports two types of bootstrapping:
Manual bootstrapping: Manual bootstrapping provides more control to developers and facilitates them regarding how and when they need to initialize the Angular app. It is useful when professionals wish to perform other tasks and operations before Angular compiles the page.
Automatic bootstrapping: As the name specifies, automatic bootstrapping is started automatically to start the Angular app. The developers need to add the ng-app directive to the application's root if they want Angular to bootstrap the application automatically. Angular loads the associated module once it finds the ng-app directive and, further, compiles the DOM.
The digest cycle process in Angular is the process that is used to monitor the watchlist to track changes in the watch variable value. There is a comparison between the present and the previous versions of the scope model values in each digest cycle.
A Component is a directive that uses shadow DOM to create encapsulated visual behavior. Usually, components are used to create UI widgets by breaking up the application into smaller parts. In short, we can say that a component is a directive-with-a-template.
A list of the major differences between a Component and a Directive in Angular:
Component | Directive |
---|---|
Components are generally used for creating UI widgets. | Directives are generally used for adding behavior to an existing DOM element. |
It is used to break up the application into smaller parts called components. | It is used to design re-usable components. |
Only one component is allowed to be used per DOM element. | Multiple directives are allowed to be used per DOM element. |
@View decorator or templateurl/template is mandatory in a component. | A Directive doesn't use View. |
A component is used to define pipes. | In a directive, it is not possible to define Pipes. |
The MVVM architecture or Model-View-ViewModel architecture is a software architectural pattern that provides a facility to developers to separate the development of the graphical user interface (the View) from the development of the business logic or back-end logic (the Model). By using this architecture, the view is not dependent on any specific model platform.
The Angular MVVM architecture consists of the following three parts:
Model: The Model consists of the structure of an entity and specifies the approach. In simple words, we can say that the model contains data of an object.
View: The View is the visual layer of the application. It specifies the structure, layout, and appearance of what a user sees on the screen. It displays the data inside the Model, represents the model, and receives the user's interaction with the view in the form of mouse clicks, keyboard input, screen tap gestures, etc., and forwards these to the ViewModel via the data binding properties. In Angular terms, the View contains the HTML template of a component.
ViewModel: The ViewModel is an abstract layer of the application. It is used to handle the logic of the application. It also manages the data of a model and displays it in the view. View and ViewModel are connected with two-way data-binding. If you make any changes in the view, the ViewModel takes a note and changes the appropriate data inside the model.
The AsyncPipe is used to subscribe to an observable or promise and return the latest value it has emitted. When a new value is emitted, the pipe marks the component that has been checked for changes.
See the following example where a time observable continuously updates the view for every 2 seconds with the current time.
In Angular, services are singleton objects that get instantiated only once during the lifetime of an application. An Angular service contains methods that are used to maintain the data throughout the life of an application. Angular services are used to organize as well as share business logic, models, or data and functions with various components of an Angular application.
Angular services offer some functions that can be invoked from an Angular component, such as a controller or directive.
Constructor is a default method in TypeScript classes that are normally used for the initialization purpose. On the other hand, the ngOnInit is specifically an Angular method and is used to define Angular bindings. Even though constructors are getting called first, it is always preferred to move all of your Angular bindings to the ngOnInit method.
See the following example how we can use ngOnInit by implementing OnInit interface as follows:
Observable: An observable is a unique object just like a promise that that is used to manage async code. Observables are not part of the JavaScript language so the developers have to rely on a popular Observable library called RxJS. The observables are created using the new keyword.
See a simple example of observable to understand it better:
Observer: Any object that has to be notified when the state of another object changes is called an observer. An observer is an interface for push-based notifications delivered by an Observable.
See the structure of an observer:
The handler that implements the observer interface for receiving observable notifications is passed as a parameter for observable as follows:
In Angular, we can categorize data binding types in three categories distinguished by the direction of data flow. These data binding categories are:
Let's see their possible binding syntax:
Data direction | Syntax | Type |
---|---|---|
From the source-to-view(One-way data binding) | 1. [target]="expression"Interpolation, Property, Attribute, Class, Style | |
From view-to-source(One-way data binding) | 1. (target)="statement" 2. on-target="statement" |
Event |
View-to-source-to-view(Two-way data binding) | 1. [(target)]="expression" 2. bindon-target="expression" |
Two-way data binding |
Multicasting or Multi-casting is the practice of broadcasting to a list of multiple subscribers in a single execution.
Let's take a simple example to demonstrate the multi-casting feature:
Angular Material is a UI component library that is used by professionals to develop consistent, attractive, and completely functional websites, web pages, and web applications. It follows the modern principles of web designing, such as graceful degradation and browser probability, and is capable of doing a lot of fascinating things in website and application development.
In Angular, the by default tendency of NgModules is eagerly loaded. It means that as soon as the app loads, all the NgModules are loaded, whether or not they are immediately necessary. That's why lazy loading is required. Lazy loading is mandatory for large apps with lots of routes. This design pattern makes the app load NgModules when they are only required. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times.
Filters are an essential part of Angular that helps in formatting the expression value to show it to the users. We can easily add filters to services, directives, templates, or controllers. We can also create personalized filters as per requirements. These filters allow us to organize the data in such a way that only the data that meets the respective criteria are displayed. Filters are placed after the pipe symbol ( | ) while used in expressions.
A list of various types of filters used in Angular:
If you create an Angular application where multiple components need to have similar functionalities, you have to do it by adding this functionality individually to every component. This is not a very easy task. Directives are used to cope up with this situation. Here, we can create a directive with the required functionality and then import the directive to components that require this functionality.