Angular 8 is the latest version which is released on May 28, 2019, by the Angular community. It is the most prominent client-side TypeScript based framework that is mainly used to create dynamic web applications. Angular 8 is very much similar to the previous version of Angular but has some more added features. You can even upgrade your Angular CLI to Angular version 8 very easily.
The key features of Angular 8 are as follows: Differential Loading to create two different production bundles of your app. New Dynamic Lazy Loading modules for imports. Supports Web Workers. Supports TypeScript version 3.4. Availability of New Workspace APIs and Builder. Bazel Support. Opt-In usage sharing. Ivy Rendering Engine: The new compiler for Angular version 8. ngUpgrade improvements.
Yes, Angular version 8 supports TypeScript 3.4 because it is mainly used to run the Angular 8 projects. Everything in Angular version 8 is written in TypeScript. So you need to upgrade your TypeScript version to 3.4.
Ivy in Angular version 8 is considered as the Rendering Engine. It was released in Angular 8 as Opt-in. It has opted as the code name for Angular’s next-generation rendering pipeline and compilation. By default, Ivy is intended to be the rendering engine in Angular 9
Bazel is one of the key features present in Angular version 8. It always allows you to build CLI applications quickly. Bazel is considered a built tool that is developed and mostly used by Google as it can build applications in any language. The entire Angular framework is built with Bazel. Moreover, Bazel allows you to break an application into different build units which are defined at the NgModule level.
Codelyzer in Angular version 8 is the open-source tool that is present on the top of the TSLint. The main purpose of Codelyzer is to verify whether the Angular TypeScript 3.4 projects are following the set of linting rules or not. It mainly focuses on the static code in Angular TypeScript. In simple words, we can say that the main purpose of the Codelyzer in Angular version 8 is to check the quality and correctness of the program.
The main purpose of the Wildcard Router in Angular version 8 is to match every URL as an instruction to get a clear client-generated view. This Wildcard route always comes last as it needs to perform its task at the end only. It is mainly used to define the route of the pages in Angular 8.
The ng -version command is used to check the current version of Angular CLI.
The following are the key advantages of Bazel, and they are as follows:
It provides you the possibility to make both frontends and backends with the same tool.
Availability of incremental build and test options. In Bazel, you have the possibility for cache and remote builds on the build farm.
The web workers in Angular version 8 are mainly used to speed up the work of the things in your application during the working of CPU. These web workers mainly allow you to run the CPU computations in a background thread. This, in turn, helps the main thread to free up and then update the user interface.
The main difference between Angular 8 and Angular 7 are as follows:
Angular 8 Angular 7 Angular 8 was released on May 28, 2019. Angular 7 was released on October 18, 2018. Angular 8 supports TypeScript version 3.4. Added support for SASS. Angular 7 supports TypeScript version 2.9. Ivy is the newly added compiler in Angular 8. Compatibility Compiler is the newly added compiler in Angular 7. This version makes Angular developer life easier and it is very easier and faster to use. It is the major release in Angular and expands the entire platform with CLI, Angular material, etc. Added Navigation type available during the Navigation in the Router. Added a new interface known as a Bootstrap interface. Added ng-command to build new projects using Bazel. Introducing a new Pipe called a KeyValuePipe. Added new mapping elements.The command ng serve is used to run and load the Angular App.
The key parts of the Angular 8 Architecture are as follows:
The components in Angular 8 are the list of classes with decorators that mainly mark their own types and provide metadata to guide Angular to do things. Every application in Angular has at least one component called a root component. This root component is mainly used to connect page hierarchy with page DOM.
NgModules in Angular version 8 varies from other JavaScript modules. Each and every Angular app has at least one module called AppModule. The NgModule provides a bootstrap mechanism to launch different applications. Commonly, every Angular App contains many functional modules to do things. The key features of Angular 8 modules are as follows:
Own functionality of the NgModule can be exported and can also be used by other NgModules.
Angular 8 NgModule can import functionalities from other NgModules.
NgUpgrade is the library present in the Angular version 8. This upgrade library is mainly used to integrate both AngularJS and Angular components in the application. Moreover, NgUpgrade also helps you in bridging the gap between the Dependency Injection Systems in both AngularJS and Angular.
The npm install -g @angular/cli@latest is the command which is used to install the latest version of Angular CLI.
The nglf directive is a structural directive present in Angular Version 8. This directive is mainly used to add or remove HTML elements based on the expression statement. The functioning of the nglf directive is observed when the expression is true the element is added and when the expression is false the element is removed using nglf directive.
The typeofchecks plays a key role in Angular 8, it is mainly used to check the type of value assigned to the variable the same as that of JavaScript. You can even test the value assigned to the object by using typeofchecks in version 8.
It is also a Structural directive present in Angular Version 8. The ngSwitch directive is mainly used to add or remove HTML DOM elements. It is much similar to the switch statement of C#. This directive is applied to a container element with the help of a switch expression.
Data Binding in Angular version 8 is considered as the key concept, that is mainly used to build the communication between the DOM and the TypeScript code of your component. It is the most prominent technique used to link your data to the view layer. Data Binding also defines interactive applications very quickly and easily. It can be achieved either by one-way binding or two-way binding.
String Interpolation in Angular version 8 comes under the one-way Data Binding technique, it is mainly used to output or extract the data from a TypeScript coding to HTML template view layer. It represents the data from the component to view layer in the form of curly braces. This interpolation technique adds the value of property to the component.
Example for String Interpolation is {{data}}
Event Binding technique is mainly used to handle the events that are raised from DOM like mouse move, button click, and many more in Angular version 8. When the DOM event occurs, at that moment only the specified method is called in the component.
The main use of Angular 8 forms is to handle the user’s input. These forms can also be used in your applications to enable the user to login, enter personal info, update profile, perform various tasks related to data entry, and many more. Basically, there are two approaches to handle the user’s input by using forms. The two approaches are used to collect the user inputs from the view layer and they also provide the way to track different changes.
The reactive forms are used in Angular 8 because of the following features. They are:
In the following cases the template-driven forms are needed in Angular 8.
The syntax to create an application in Angular version 8 is
ng new app_name The npm install -g @angular/cli is the command used to install Angular CLI.
The Angular Universal is defined as the process of SSR (server-side rendering) of your particular application to HTML present on the Server. Basically, all the Angular applications are single-page applications so the rendering always occurs on the browser. The entire process of rendering single-page applications is known as the client-side rendering process (CSR).
The following are the advantages of Angular 8, and they are as follows:
Angular is a TypeScript-based open-source web application framework, developed and maintained by Google. It offers an easy and powerful way of building front end web-based applications.
Angular integrates a range of features like declarative templates, dependency injection, end-to-end tooling, etc. that facilitates web application development.
Traditionally, VanillaJS and jQuery were used by developers to develop dynamic websites. As the websites became more complex with added features and functionality, it was hard for the developers to maintain the code. Moreover, there was no provision of data handling facilities across the views by jQuery. So, Angular was built to address these issues, thus, making it easier for the developers by dividing code into smaller bits of information that are known as Components in Angular.
Client-side frameworks permit the development of advanced web applications like SPAs which, if developed by VanillaJS, is a slower process.
Conventional HTML elements have some content between the tags. For instance:
<p>Put your paragraph here</p>
Now consider the following example of having custom text between angular tags:
<app-work>This won’t work like HTML until you use ng-content Directive</app-work>
However, doing so won’t work the way it worked for HTML elements. In order to make it work just like the HTML example mentioned above, we need to use the ng-content Directive. Moreover, it is helpful in building reusable components.
Know more about the ng-content directive.
There are several features of Angular that make it an ideal front end JavaScript framework. Most important of them are described as follows:
Angular allows creating accessible applications using ARIA-enabled components, built-in a11y test infrastructure, and developer guides.
Angular provides support for command-line interface tools. These tools can be used for adding components, testing, instant deploying, etc.
Angular’s intuitive API allows the creation of high-performance, complex animation timelines with very little code.
Angular can be used for building an efficient and powerful desktop, native, and progressive web apps. Angular provides support for building native mobile applications using Cordova, Ionic, or NativeScript.
Angular allows creating high performance, offline, and zero-step installation progressive web apps using modern web platform capabilities. The popular JS framework can also be used for building desktop apps for Linux, macOS, and Windows.
Angular is able to convert templates into highly-optimized code for modern JavaScript virtual machines.
With the new Component Router, Angular apps load quickly. The Component Router offers automatic code-splitting so that only the code required to render the view that is requested by a user is loaded.
Angular offers code completion, instant errors, etc. with popular source code editors and IDEs.
Allows creating UI views with a simple and powerful template syntax.
Angular lets you carry out frequent unit tests using Karma. The Protractor allows running faster scenario tests in a stable way.
Out of box Features: Several built-in features like routing, state management, rxjs library, and HTTP services are straight out of the box services provided by Angular. So, one does not need to look for the above-stated features separately.
Declarative UI: Angular uses HTML to render the UI of an application as it is a declarative language and is much easier to use than JavaScript.
Long-term Google Support: Google plans to stick with Angular and further scale up its ecosystem as it has offered its long term support to Angular.
Parameters | AngularJS | Angular |
Architecture | MVC or Model-View-Controller architecture facilitates the AngularJS framework, where the Model contains the business logic and Controllers processes information, lastly, View shows the information present in the Model. | Angular replaces controllers with Components that are directives with a predefined template. |
Language | AngularJS uses JavaScript language, which is a dynamically typed language. | Angular uses TypeScript language, a statically typed language, and a superset of JavaScript. Angular provides better performance while developing larger applications. |
Mobile Support | Does not support mobile support. | Supported by all popular mobile browsers. |
Structure | The process of maintaining code becomes tedious in the case of larger applications. | It is easier to maintain code for larger applications as it provides a better structure. |
Expression Syntax | A developer needs to remember the correct ng-directive for binding an event or a property. | Property binding is done using "[ ]" attribute and event binding is done using "( )" attribute. |
Routing | AngularJS uses $routeprovider.when() | Angular uses @RouteConfig{(…)} |
Speed | The development effort and time are reduced significantly because of the two-way data binding | Angular is faster due to upgraded features. |
Dependency Injection | AngularJS doesn’t support DI. | Angular supports a hierarchical Dependency Injection with unidirectional tree-based change detection. |
Support | No official support or updates are available for AngularJS. | Angular has active support with updates rolling out every now and then. |
Angular components enter its lifecycle from the time it is created to the time it is destroyed. Angular hooks provide ways to tap into these phases and trigger changes at specific phases in a lifecycle.
ngOnChanges( ): This method is called whenever one or more input properties of the component changes. The hook receives a SimpleChanges object containing the previous and current values of the property.
ngOnInit( ): This hook gets called once, after the ngOnChanges hook.
It initializes the component and sets the input properties of the component.
ngDoCheck( ): It gets called after ngOnChanges and ngOnInit and is used to detect and act on changes that cannot be detected by Angular.
We can implement our change detection algorithm in this hook.
ngAfterContentInit( ): It gets called after the first ngDoCheck hook. This hook responds after the content gets projected inside the component.
ngAfterContentChecked( ): It gets called after ngAfterContentInit and every subsequent ngDoCheck. It responds after the projected content is checked.
ngAfterViewInit( ): It responds after a component's view, or a child component's view is initialized.
ngAfterViewChecked( ): It gets called after ngAfterViewInit, and it responds after the component's view, or the child component's view is checked.
ngOnDestroy( ): It gets called just before Angular destroys the component. This hook can be used to clean up the code and detach event handlers.
Yes, we can, with Angular Universal, a technology provided by Angular capable of rendering applications on the server-side.
The benefits of using Angular Universal are:
Dependency injection is an application design pattern that is implemented by Angular and forms the core concepts of Angular.
Let us understand in a detailed manner. Dependencies in Angular are services which have a functionality. Various components and directives in an application can need these functionalities of the service. Angular provides a smooth mechanism by which these dependencies are injected into components and directives.
MVVM architecture removes tight coupling between each component. The MVVM architecture comprises of three parts:
The architecture allows the children to have reference through observables and not directly to their parents.
Following code demonstrates how to navigate between different routes in an Angular app dubbed “Some Search App”:
import from "@angular/router"; . . . @Component({ selector: 'app-header', template: ` <nav class="navbar navbar-light bg-faded"> <a class="navbar-brand" (click)="goHome()">Some Search App</a> <ul class="nav navbar-nav"> <li class="nav-item"> <a class="nav-link" (click)="goHome()">Home</a> </li> <li class="nav-item"> <a class="nav-link" (click)="goSearch()">Search</a> </li> </ul> </nav> ` }) class HeaderComponent { constructor(private router: Router) {} goHome() { this.router.navigate(['']); } goSearch() { this.router.navigate(['search']); } }
An angular application consists of components and templates which a browser cannot understand. Therefore, every Angular application needs to be compiled before running inside the browser. The Angular compiler takes in the JS code, compiles it, and then produces some JS code. It is known as AOT compilation and happens only once per occasion per user.
There are two kinds of compilation that Angular provides:
JIT(Just-in-Time) compilation: the application compiles inside the browser during runtime
AOT(Ahead-of-Time) compilation: the application compiles during the build time.
Advantages of AOT compilation:
Answer: Singleton objects in Angular that get instantiated only once during the lifetime of an application are called services. An Angular service contains methods that maintain the data throughout the life of an application.
The primary intent of an Angular service is to organize as well as share business logic, models, or data and functions with various components of an Angular application.
The functions offered by an Angular service can be invoked from any Angular component, such as a controller or directive.
Following are the various advantages of using Angular:
Disadvantages of using Angular are enumerated as follows:
Unlike the previous versions of Angular, the 7th major release comes with splitting in @angular/core. This is done in order to reduce the size of the same. Typically, not each and every module is required by an Angular developer. Therefore, in Angular 7 each split of the @angular/core will have no more than 418 modules.
Also, Angular 7 brings drag-and-drop and virtual scrolling into play. The latter enables loading as well as unloading elements from the DOM. For virtual scrolling, the latest version of Angular comes with the package. Furthermore, Angular 7 comes with a new and enhanced version of the ng-compiler.
Also referred to as moustache syntax, string interpolation in Angular refers to a special type of syntax that makes use of template expressions in order to display the component data. These template expressions are enclosed within double curly braces i.e. {{ }}.
The JavaScript expressions that are to be executed by Angular are added within the curly braces and the corresponding output is embedded into the HTML code. Typically, these expressions are updated and registered like watches as a part of the digest cycle.
Answer: The user login credentials are passed to an authenticate API, which is present on the server. Post server-side validation of the credentials, a JWT (JSON Web Token) is returned. The JWT has information or attributes regarding the current user. The user is then identified with the given JWT. This is called authentication.
Post logging-in successfully, different users have a different level of access. While some may access everything, access for others might be restricted to only some resources. The level of access is authorization.
Here is a detailed post on Angular 7 - JWT Authentication Example & Tutorial: http://jasonwatmore.com/post/2018/11/16/angular-7-jwt-authentication-example-tutorial
Angular organizes the $scope objects into a hierarchy that is typically used by views. This is known as 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 a typical representation of a Scope Hierarchy:
ng generate class Dummy [options]
This will generate a class named Dummy.
Following are the various notable differences between Angular and Backbone.js
Backbone.js makes use of the MVP architecture and doesn’t offer any data binding process. Angular, on the contrary, works on the MVC architecture and makes use of two-way data binding for driving application activity.
Being backed by Google greatly ups the community support received by the Angular framework. Also, extensive documentation is available. Although Backbone.js has a good level of community support, it only documents on Underscore.js templates, not much else.
Angular uses two-way data binding process and thus is a bit complex. Backbone.js, on the contrary, doesn’t have any data binding process and thus, has a simplistic API.
The prime focus of Angular JS is upon valid HTML and dynamic elements that imitate the underlying data for rebuilding the DOM as per the specified rules and then works on the updated data records.
Backbone.js follows the direct DOM manipulation approach for representing data and application architecture changes.
Thanks to its two-way data binding functionality, Angular offers an impactful performance for both small and large projects.
Backbone.js has a significant upper hand in performance over Angular in small data sets or small webpages. However, it is not recommended for larger webpages or large data sets due to the absence of any data binding process.
Angular supports templating via dynamic HTML attributes. These are added to the document to develop an easy to understand application at a functional level. Unlike Angular, Backbone.js uses Underscore.js templates that aren’t fully-featured as Angular templates.
The approach to testing varies greatly between Angular and Backbone.js due to the fact that while the former is preferred for building large applications the latter is ideal for developing smaller webpages or applications.
For Angular, unit testing is preferred and the testing process is smoother through the framework. In the case of Backbone.js, the absence of a data binding process allows for a swift testing experience for a single page and small applications.
Angular is an open-source JS-based front-end web application framework that extends HTML with new attributes. On the other hand, Backbone.js is a lightweight JavaScript library featuring a RESTful JSON interface and MVP framework.
As soon as a promise is made, the execution takes place. However, this is not the case with observables because they are lazy. This means that nothing happens until a subscription is made. While promises handle a single event, observable is a stream that allows passing of more than one event. A callback is made for each event in an observable.
Various differences between Angular and AngularJS are stated as follows:
Directives. The image represents the types of directives in Angular; Attribute, structural, and custom.
Written with HTML, templates in Angular contains Angular-specific attributes and elements. Combined with information coming from the controller and model, templates are then further rendered to cater the user with the dynamic view.
In Angular, annotations are used for creating an annotation array. They are only metadata set of the class using the Reflect Metadata library.
Decorators in Angular are design patterns used for separating decoration or modification of some class without changing the original source code.
Directives are one of the core features of Angular. They allow an Angular developer to write new, application-specific HTML syntax. In actual, directives are functions that are executed by the Angular compiler when the same finds them in the DOM. Directives are of three types:
There are essentially 9 building blocks of an Angular application. These are:
Answer: The single biggest difference between Angular and jQuery is that while the former is a JS frontend framework, the latter is a JS library. Despite this, there are some similarities between the two, such as both features DOM manipulation and provides support for animation.
Nonetheless, notable differences between Angular and jQuery are:
Although both Angular expressions and JavaScript expressions can contain literals, operators, and variables, there are some notable dissimilarities between the two. Important differences between Angular expressions and JavaScript expressions are enlisted below:
You can draw some like this:
Here is Angular Architecture in detail: https://angular.io/guide/architecture
It is a UI component library. Angular Material helps in creating attractive, consistent, and fully functional web pages as well as web applications. It does so while following modern web design principles, including browser portability and graceful degradation.
Each Angular app gets compiled internally. The Angular compiler takes in the JS code, compiles it and then produces some JS code. This happens only once per occasion per user. It is known as AOT (Ahead-Of-Time) compilation.
In order to connect application data with the DOM (Data Object Model), data binding is used. It happens between the template (HTML) and component (TypeScript). There are 3 ways to achieve data binding:
This represents a dependency injection or DI.
Used for the business layer of the application, the service() function operates as a constructor function. The function is invoked at runtime using the new keyword.
Although the factory() function works in pretty much the same way as the service() function does, the former is more flexible and powerful. In actual, the factory() function are design patterns that help in creating objects.
The process of monitoring the watchlist in order to track changes in the value of the watch variable is termed the digest cycle in Angular. The previous and present versions of the scope model values are compared in each digest cycle.
Although the digest cycle process gets triggered implicitly, it is possible to start it manually by using the $apply() function.
In order to format the value of expression so that it can be displayed to the user, AngularJS has filters. It is possible to add these filters to the controllers, directives, services, or templates. AngularJS also provides support for creating custom filters.
Organizing data in such a way so that it is displayed only when certain criteria are fulfilled is made possible using filters. Filters are added to the expressions using the pipe ‘|’ character. Various types of AngularJS filters are enumerated as follows:
Here are some of the new aspects introduced in Angular 6:
ngOnInit() is a lifecycle hook that is called after Angular has finished initializing all data-bound properties of a directive. It is defined as:
Interface OnInit { ngOnInit() : void }
Answer: In the SPA technology, only a single page, which is index.HTML, is maintained although the URL keeps on changing. Unlike traditional web technology, SPA technology is faster and easy to develop as well.
In conventional web technology, as soon as a client requests a webpage, the server sends the resource. However, when again the client requests for another page, the server responds again with sending the requested resource. The problem with this technology is that it requires a lot of time.
We create a decorator called Dummy:
function Dummy(target) { dummy.log('This decorator is Dummy', target); }
It is called Transpiling. Even though TypeScript is used for writing code in Angular applications, it gets internally transpiled into equivalent JavaScript.
Answer:To put simply, ViewEncapsulation determines whether the styles defined in a particular component will affect the entire application or not. Angular supports 3 types of ViewEncapsulation:
TypeScript is a superset of Javascript as it is Javascript + Types or extra features like typecasting for variables, annotations, variable scope and much more. The typescript is designed in a way to overcome Javascript shortcomings like typecasting of variables, classes, decorators, variable scope and many more. Moreover, Typescript is purely object-oriented programming that offers a "Compiler" that can convert to Javascript-equivalent code.
Components and directive of Angular JS follow the following typical lifecycle.
Following are the features:
1. Added ng update
CLI command updates angular project dependencies to their latest versions. The ng update is a normal package manager tool to identify and update in normal package manager tools to identify and update other dependencies.
2. Uses RxJS6
This is the third party library (RxJS) and introduces two important changes as compared to RxJS5.
To update of RxJS6, run the following command:
npm install --save rxjs@6
To update your existing Angular Project, run the following:
npm install --save rxjs-compat
3. The <ng-template>
Angular 6 uses <ng-template> instead of <template>
4. Service Level Changes
If in an earlier version, the user wanted to provide a service to the entire application, the user was required to add it to providers in the AppModule but it is not required in the case of Angular6.
5. Renamed Operators
Angular 6 has renamed following operators:
Traditionally, VanillaJS and jQuery were used by developers to develop dynamic websites. As the websites became more complex with added features and functionality, it was hard for the developers to maintain the code. Moreover, there was no provision of data handling facilities across the views by jQuery. So, Angular was built to address these issues, thus, making it easier for the developers by dividing code into smaller bits of information that are known as Components in Angular. Client-side frameworks permit the development of advanced web applications like SPAs which, if developed by VanillaJS, is a slower process.
Parameters | AngularJS | Angular |
Architecture | MVC or Model-View-Controller architecture facilitates the AngularJS framework, where the Model contains the business logic and Controllers processes information, lastly, View shows the information present in the Model. | Angular replaces controllers with Components that are directives with a predefined template. |
Language | AngularJS uses JavaScript language, which is a dynamically typed language. | Angular uses TypeScript language, a statically typed language, and a superset of JavaScript. Angular provides better performance while developing larger applications. |
Mobile Support | Does not support mobile support. | Supported by all popular mobile browsers. |
Structure | The process of maintaining code becomes tedious in the case of larger applications. | It is easier to maintain code for larger applications as it provides a better structure. |
Expression Syntax | A developer needs to remember the correct ng-directive for binding an event or a property. | Property binding is done using "[ ]" attribute and event binding is done using "( )" attribute. |
Routing | AngularJS uses $routeprovider.when() | Angular uses @RouteConfig{(…)} |
Speed | The development effort and time are reduced significantly because of the two-way data binding | Angular is faster due to upgraded features. |
Dependency Injection | AngularJS doesn’t support DI. | Angular supports a hierarchical Dependency Injection with unidirectional tree-based change detection. |
Support | No official support or updates are available for AngularJS. | Angular has active support with updates rolling out every now and then. |
Advantages of AOT compilation:
Angular components enter its lifecycle from the time it is created to the time it is destroyed. Angular hooks provide ways to tap into these phases and trigger changes at specific phases in a lifecycle.
Yes, we can, with Angular Universal, a technology provided by Angular capable of rendering applications on the server-side. The benefits of using Angular Universal are:
Dependency injection is an application design pattern that is implemented by Angular and forms the core concepts of Angular. Let us understand in a detailed manner. Dependencies in Angular are services which have a functionality. Various components and directives in an application can need these functionalities of the service. Angular provides a smooth mechanism by which these dependencies are injected into components and directives.
MVVM architecture removes tight coupling between each component. The MVVM architecture comprises of three parts:
The architecture allows the children to have reference through observables and not directly to their parents.
Yes, they can be considered as Angular 6 Interview Question.
Back in the day, web developers used VanillaJS and jQuery to develop dynamic websites but, as the logic of one's website grew, the code became more and more tedious to maintain. For applications that use complex logic, developers had to put in extra effort to maintain separation of concerns for the app. Also, jQuery did not provide facilities for data handling across views. For tackling the above problems, client-side frameworks like Angular came into the picture, which made life easier for the developers by handling separation of concerns and dividing code into smaller bits of information (In the case of Angular, called Components). Client-side frameworks allow one to develop advanced web applications like Single-Page-Application. Not that we cannot develop SPAs using VanillaJS, but by doing so, the development process becomes slower.
Every Angular app consists of a file named angular.json. This file will contain all the configurations of the app. While building the app, the builder looks at this file to find the entry point of the application. Following is an image of the angular.json file:
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/angular-starter",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": false,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
"src/style.css"
]
}
}
Inside the build section, the main property of the options object defines the entry point of the application which in this case is main.ts. The main.ts file creates a browser environment for the application to run, and, along with this, it also calls a function called bootstrapModule, which bootstraps the application. These two steps are performed in the following order inside the main.ts file:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
platformBrowserDynamic().bootstrapModule(AppModule)
In the above line of code, AppModule is getting bootstrapped. The AppModule is declared in the app.module.ts file. This module contains declarations of all the components. Below is an example of app.module.ts file:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
entryComponents: [],
bootstrap: [AppComponent]
})
export class AppModule { }
As one can see in the above file, AppComponent is getting bootstrapped. This component is defined in app.component.ts file. This file interacts with the webpage and serves data to it. Below is an example of app.component.ts file:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular';
}
Each component is declared with three properties: 1. Selector - used for accessing the component 2. Template/TemplateURL - contains HTML of the component 3. StylesURL - contains component-specific stylesheets After this, Angular calls the index.html file. This file consequently calls the root component that is app-root. The root component is defined in app.component.ts. This is how the index.html file looks:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<app-root></app-root>
</body>
</html>
The HTML template of the root component is displayed inside the <app-root>
tags.
This is how every angular application works.
Architecture
AngularJS uses MVC or Model-View-Controller architecture, where the Model contains the business logic, Controller processes information and View shows the information present in the Model. Angular replaces controllers with Components. Components are nothing but directives with a predefined template.
Language
AngularJS uses JavaScript language, which is a dynamically typed language. Angular uses TypeScript language, which is a statically typed language and is a superset of JavaScript. By using statically typed language, Angular provides better performance while developing larger applications.
Mobile Support
AngularJS does not provide mobile support. Angular is supported by all popular mobile browsers.
Structure
While developing larger applications, the process of maintaining code becomes tedious in the case of AngularJS. In the case of Angular, it is easier to maintain code for larger applications as it provides a better structure.
Expression Syntax
While developing an AngularJS application, a developer needs to remember the correct ng-directive for binding an event, or a property. Whereas in Angular, property binding is done using "[ ]" attribute and event binding is done using "( )" attribute.
Every Angular application consists of components and templates which the browser cannot understand. Therefore, all the Angular applications need to be compiled first before running inside the browser. Angular provides two types of compilation:
In JIT compilation, the application compiles inside the browser during runtime. Whereas in the AOT compilation, the application compiles during the build time. The advantages of using AOT compilation are:
By default, angular builds and serves the application using JIT compiler:
ng build ng serve
For using AOT compiler following changes should be made:
ng build --aot ng serve --aot
For better understanding, I would like you to create an Angular application by running the following inside the command terminal:
ng new angularApp
The above command will create an angular application in the directory. Next, let's move on to understand Components, Modules, and Services. Components In Angular, components are the basic building blocks, which control a part of the UI for any application. A component is defined using the @Component decorator. Every component consists of three parts, the template which loads the view for the component, a stylesheet which defines the look and feel for the component, and a class that contains the business logic for the component. For creating a component, inside the command terminal, navigate to the directory of the application created, and run the following command:
ng generate component test
Or
ng g c test
One can see the generated component inside src/app/test folder. The component will be defined inside test.component.ts and this is how it looks:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export lass TestComponent implements OnInit {
constructor() {}
ngOnInit() {
}
}
As we can see in the above image, our component is defined with @Component decorator.
Modules A module is a place where we can group components, directives, services, and pipes. Module decides whether the components, directives, etc can be used by other modules, by exporting or hiding these elements. Every module is defined with a @NgModule decorator. By default, modules are of two types:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { TestComponent } from './test/text.component';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
We can see in the above image that the component we created earlier is already imported in the declarations array. To create a feature module, run the following command:
ng g m test-module
The module is created inside the src/app/test-module/test-module.module.ts file:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
@NgModule({
declarations: [],
imports: [
CommonModule
]
})
export class TestModuleModule { }
As one can see, CommonModule is imported since this is a feature module.
Services Services are objects which get instantiated only once during the lifetime of an application. The main objective of a service is to share data, functions with different components of an Angular application. A service is defined using a @Injectable decorator. A function defined inside a service can be invoked from any component or directive. To create a service, run the following command:
ng g s test-service
The service will be created inside src/app/test-service.service.ts:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TestServiceService {
constructor() { }
}
Any method/function defined inside the TestServiceService class can be directly used inside any component by just importing the service.
Every component in Angular has a lifecycle, different phases it goes through from the time of creation to the time it's destroyed. Angular provides hooks to tap into these phases and trigger changes at specific phases in a lifecycle.
ngOnChanges( ) This hook/method is called before ngOnInit and whenever one or more input properties of the component changes.
This method/hook receives a SimpleChanges object which contains the previous and current values of the property.
ngOnInit( ) This hook gets called once, after the ngOnChanges hook.
It initializes the component and sets the input properties of the component.
ngDoCheck( ) It gets called after ngOnChanges and ngOnInit and is used to detect and act on changes that cannot be detected by Angular.
We can implement our change detection algorithm in this hook. ngAfterContentInit( ) It gets called after the first ngDoCheck hook. This hook responds after the content gets projected inside the component.
ngAfterContentChecked( ) It gets called after ngAfterContentInit and every subsequent ngDoCheck. It responds after the projected content is checked.
ngAfterViewInit( ) It responds after a component's view, or a child component's view is initialized.
ngAfterViewChecked( ) It gets called after ngAfterViewInit, and it responds after the component's view, or the child component's view is checked.
ngOnDestroy( ) It gets called just before Angular destroys the component. This hook can be used to clean up the code and detach event handlers.
Let’s understand how to use ngOnInit hook, since it’s the most oftenly used hook. If one has to process lot of data during component creation, it’s better to do it inside ngOnInit hook rather than the constructor:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
constructor() { }
ngOnInit() {
this.processData();
}
processData(){
// Do something..
}
}
As you can see we have imported OnInit but we have used ngOnInit function. This principle should be used with the rest of the hooks as well.
String interpolation and property binding are parts of data-binding in Angular. Data-binding is a feature in angular, which provides a way to communicate between the component(Model) and its view(HTML template). Data-binding can be done in two ways, one-way binding and two-way binding. In Angular, data from the component can be inserted inside the HTML template. In one-way binding, any changes in the component will directly reflect inside the HTML template but, vice-versa is not possible. Whereas, it is possible in two-way binding. String interpolation and property binding allow only one-way data binding. String interpolation uses the double curly braces {{ }} to display data from the component. Angular automatically runs the expression written inside the curly braces, for example, {{ 2 + 2 }} will be evaluated by Angular and the output 4, will be displayed inside the HTML template. Using property binding, we can bind the DOM properties of an HTML element to a component's property. Property binding uses the square brackets [ ] syntax.
The first and perhaps, the biggest difference is that Angular expressions allow us to write JavaScript in HTML which is not the case when it comes to JavaScript expressions. Next, Angular expressions are evaluated against a local scope object whereas JavaScript expressions against global window object. Let's understand that better with an example : Consider the following component named test:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
template: `
<h4>{{message}}</h4>
`,
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
message:string = “Hello world”;
constructor() { }
ngOnInit() {
}
}
As one can see that Angular expression is used to display message property of a component. Since we are using Angular expressions, in the present template, we cannot access a property outside of its local scope, which in this case is TestComponent. This proves that Angular expressions are always evaluated based on scope object rather than the global object. Next difference is how Angular expressions handle null and undefined. Consider the following JavaScript example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Test</title>
</head>
<body>
<div id="foo"><div>
</body>
<script>
'use strict';
let bar = {};
document.getElementById('foo').innerHTML = bar.x;
</script>
</html>
If you run the above code, you will see undefined displayed on the screen. Although it’s not ideal to leave any property undefined, the user does not need to see this. Now consider the following Angular example:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-new',
template: `
<h4>{{message}}</h4>
`,
styleUrls: ['./new.component.css']
})
export class NewComponent implements OnInit {
message:object = {};
constructor() { }
ngOnInit() {
}
}
If you render the above component, you will not see undefined being displayed on the screen. Next, in Angular expressions one cannot use loops, conditionals and exceptions. The difference which makes Angular expressions quite beneficial is the use of pipes. Angular uses pipes(called filters in AngularJS), which can be used to format data before displaying it. Let’s see one predefined pipe in action:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-new',
template: `
<h4>{{message | lowercase}}</h4>
`,
styleUrls: ['./new.component.css']
})
export class NewComponent implements OnInit {
message:string = "HELLO WORLD";
constructor() { }
ngOnInit() {
}
}
In the above code we have used a predefined pipe called lowercase, which transforms all the letters in lowercase. Therefore, if you render the above component, you will see “hello world” being displayed. In contrast, JavaScript does not have the concept of pipes.
The first difference is that an Observable is lazy whereas a Promise is eager.
Promise | Observable |
Emits a single value | Emits multiple values over a period of time |
Not Lazy |
Lazy. An observable is not called until we subscribe to the observable |
Cannot be cancelled |
Can be cancelled by using the unsubscribe() method |
Observable provides operators like map, forEach, filter, reduce, retry, retryWhen etc. |
const observable = rxjs.Observable.create(observer => {
console.log('Text inside an observable');
observer.next('Hello world!');
observer.complete();
});
console.log('Before subscribing an Observable');
observable.subscribe((message)=> console.log(message));
When you run the above Observable, you can see messages being displayed in the following order:
Before subscribing an Observable Text inside an observable Hello world!
As you can see, observables are lazy. Observable runs only when someone subscribes to them hence, the message “Before subscribing…” is displayed ahead of the message inside the observable. Now let’s consider a Promise:
const promise = new Promise((resolve, reject) => {
console.log('Text inside promise');
resolve('Hello world!');
});
console.log('Before calling then method on Promise');
greetingPoster.then(message => console.log(message));
Running the above promise, the messages will be displayed in the following order:
Text inside promise Before calling then method on Promise Hello world!
As you can see the message inside Promise is displayed first. This means that a promise runs before the then method is called. Therefore, promises are eager. The next difference is that Promises are always asynchronous. Even when the promise is immediately resolved. Whereas an Observable, can be both synchronous and asynchronous. The above example of an observable is the case to show that an observable is synchronous. Let’s see the case where an observable can be asynchronous:
const observable = rxjs.Observable.create(observer => {
setTimeout(()=>{
observer.next('Hello world');
observer.complete();
},3000)
});
console.log('Before calling subscribe on an Observable');
observable.subscribe((data)=> console.log(data));
console.log('After calling subscribe on an Observable');
The messages will be displayed in the following order:
Before calling subscribe on an Observable After calling subscribe on an Observable Hello world!
You can see in this case, observable runs asynchronously. The next difference is that Observables can emit multiple values whereas Promises can emit only one value. The biggest feature of using observables is the use of operators. We can use multiple operators on an observable whereas, there is no such feature in a promise.
Can one make an angular application to render on the server-side? Yes, angular provides a technology called Angular Universal, which can be used to render applications on the server-side. The advantages of using Angular Universal are :
A directive is a class in Angular that is declared with a @Directive decorator. Every directive has its own behaviour and can be imported into various components of an application. When to use a directive? Consider an application, where multiple components need to have similar functionalities. The norm thing to do is by adding this functionality individually to every component but, this task is tedious to perform. In such a situation, one can create a directive having the required functionality and then, import the directive to components which require this functionality. Types of directives Component directives These form the main class in directives. Instead of @Directive decorator we use @Component decorator to declare these directives. These directives have a view, a stylesheet and a selector property. Structural directives These directives are generally used to manipulate DOM elements. Every structural directive has a ‘ * ’ sign before them. We can apply these directives to any DOM element. Let’s see some built-in structural directives in action:
<div *ngIf="isReady" class="display_name">
{{name}}
</div>
<div class="details" *ngFor="let x of details" >
<p>{{x.name}}</p>
<p> {{x.address}}</p>
<p>{{x.age}}</p>
</div>
In the above example, we can *ngIf and *ngFor directives being used. *ngIf is used to check a boolean value and if it’s truthy,the div element will be displayed. *ngFor is used to iterate over a list and display each item of the list. Attribute Directives These directives are used to change the look and behaviour of a DOM element. Let’s understand attribute directives by creating one: How to create a custom directive? We’re going to create an attribute directive: In the command terminal, navigate to the directory of the angular app and type the following command to generate a directive:
ng g directive blueBackground
The following directive will be generated. Manipulate the directive to look like this:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appBlueBackground]'
})
export class BlueBackgroundDirective {
constructor(el:ElementRef) {
el.nativeElement.style.backgroundColor = "blue";
}
}
Now we can apply the above directive to any DOM element:
<p appBlueBackground>Hello World!</p>
Following are the commonly used methods by which one can pass data between components in angular:
Parent to child using @Input decorator Consider the following parent component:
@Component({
selector: 'app-parent',
template: `
<app-child [data]=data></app-child>
` ,
styleUrls: ['./parent.component.css']
})
export class ParentComponent{
data:string = "Message from parent";
constructor() { }
}
In the above parent component, we are passing “data” property to the following child component:
import { Component, Input} from '@angular/core';
@Component({
selector: 'app-child',
template:`
<p>{{data}}</p>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() data:string
constructor() { }
}
In the child component, we are using @Input decorator to capture data coming from a parent component and using it inside the child component’s template.
Child to parent using @ViewChild decorator Child component:
import {Component} from '@angular/core';
@Component({
selector: 'app-child',
template:`
<p>{{data}}</p>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
data:string = "Message from child to parent";
constructor() { }
}
Parent Component
import { Component,ViewChild, AfterViewInit} from '@angular/core';
import { ChildComponent } from './../child/child.component';
@Component({
selector: 'app-parent',
template: `
<p>{{dataFromChild}}</p>
` ,
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements AfterViewInit {
dataFromChild: string;
@ViewChild(ChildComponent,{static:false}) child;
ngAfterViewInit(){
this.dataFromChild = this.child.data;
}
constructor() { }
}
In the above example, a property named “data” is passed from the child component to the parent component. @ViewChild decorator is used to reference the child component as “child” property. Using the ngAfterViewInit hook, we assign the child’s data property to the messageFromChild property and use it in the parent component’s template. Child to parent using @Output and EventEmitter In this method, we bind a DOM element inside the child component, to an event ( click event for example ) and using this event we emit data that will captured by the parent component: Child Component:
import {Component, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'app-child',
template:`
<button (click)="emitData()">Click to emit data</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
data:string = "Message from child to parent";
@Output() dataEvent = new EventEmitter<string>();
constructor() { }
emitData(){
this.dataEvent.emit(this.data);
}
}
As you can see in the child component, we have used @Output property to bind an EventEmitter. This event emitter emits data when the button in the template is clicked. In the parent component’s template we can capture the emitted data like this:
<app-child (dataEvent)="receiveData($event)"></app-child>
Then inside the receiveData function we can handle the emitted data:
receiveData($event){
this.dataFromChild = $event;
}
Dependency injection is an application design pattern which is implemented by Angular. It also forms one of the core concepts of Angular. So what is dependency injection in simple terms? Let’s break it down, dependencies in angular are nothing but services which have a functionality. Functionality of a service, can be needed by various components and directives in an application. Angular provides a smooth mechanism by which we can inject these dependencies in our components and directives. So basically, we are just making dependencies which are injectable across all components of an application.
Let’s understand how DI (Dependency Injection) works: Consider the following service, which can be generated using:
ng g service test
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TestService {
importantValue:number = 42;
constructor() { }
returnImportantValue(){
return this.importantValue;
}
}
As one can notice, we can create injectable dependencies by adding the @Injectable decorator to a class. We inject the above dependency inside the following component:
import { TestService } from './../test.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
value:number;
constructor(private testService:TestService) { }
ngOnInit() {
this.value = this.testService.returnImportantValue();
}
}
One can see we have imported our TestService at the top of the page. Then, we have created an instance inside the constructor of the component and implemented the returnImportantValue function of the service. From the above example, we can observe how angular provides a smooth way to inject dependencies in any component.
MVVM architecture consists of three parts: 1. Model 2. View 3. ViewModel
Model contains the structure of an entity. In simple terms it contains data of an object. View is the visual layer of the application. It displays the data contained inside the Model. In angular terms, this will be the HTML template of a component. ViewModel is an abstract layer of the application. A viewmodel handles the logic of the application. It manages the data of a model and displays it in the view. View and ViewModel are connected with data-binding (two-way data-binding in this case). Any change in the view, the viewmodel takes a note and changes the appropriate data inside the model.