A list of top frequently asked Angular interview questions and answers are given below.
Angular JS is a JavaScript based web application framework which is based on MVW (Model View Whatever) based design pattern. Angular JS framework was developed by Google. It was initially released in the year 2010. It was licensed under MIT License. It was completely written in JavaScript. Angular 4 version was released in the year 2017. An angular framework is mainly based on Typescript.
Angular 4 was released immediately after Angular 2 instead of Angular 3 with major features and as a break through release. It supports cross platform and can be used to develop Single Page Applications in web application development.
Web development has come a long way in delivering functionalities online. There are tremendous changes happening both on the client-side technologies (like JS/Angular) and the server side technologies (like Java/Spring). Not only AngularJS, similar technologies like React JS and Vue JS are offering great scope in client development. Let us see what Angular has to offer in client development.
AngularJS has been introduced by the giant, Google. AngularJS is a Javascript framework that helps you to create dynamic Web apps. Normally, AngularJS uses HTML as the backbone. AngularJS creates extended HTML tags that can be used as normal HTML tags. These tags will help you to write an efficient code. The interesting fact is that you can reduce the lines of code you may need to write when you use normal JavaScript.
AngularJS is based on three components:
AngularJS extends HTML attributes with Directives and binds data to HTML with Expressions.
The template is the HTML portion of the angular app. It is exactly like a static HTML page, except that templates contain additional syntax which allows data to be injected in it in order to provide a customized user experience.
The features of AngularJS are
Scope refers to the application model, it acts like glue between application controller and the view. Scopes are arranged in hierarchical structure and impersonate the DOM ( Document Object Model) structure of the application. It can watch expressions and propagate events.
The controller is a function which generally takes an empty scope object as a parameter and adds to it the fields and functions that will be later exposed to the user via the view.
AngularJS directives are only used to extend HTML and DOM elements' behavior. These are the special attributes, that start with ng- prefix, that tell AngularJS's HTML compiler ($compile) to attach a specified behavior to that DOM element.
We can create our own directives for Angular to use them in our AngularJS Application with the controllers and services too
AngularJS Services are objects that provide separation of concerns to an AngularJS app. These can be created using a factory method or a service method. Services are singleton components and all components of the application (into which the service is injected) will work with single instance of the service. An AngularJS service allows developing of business logic without depending on the View logic which will work with it.
Few of the inbuilt services in AngularJS are:
the $http
service: The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser’s XMLHttpRequest object or via JSONP
the $log
service: Simple service for logging. Default implementation safely writes the message into the browser’s console
the $anchorScroll
: it scrolls to the element related to the specified hash or (if omitted) to the current value of $location.hash() Why should one know about AngularJS Services, you may ask. Well, understanding the purpose of AngularJS Services helps bring modularity to AngularJS code
Services are the best may to evolve reusable API within and AngularJS app.
service()
method or the factory()
method.AngularJS digest cycle is the process behind Angular JS data binding. In each digest cycle, Angular compares the old and the new version of the scope model values. The digest cycle is triggered automatically. We can also use $apply() if we want to trigger the digest cycle manually.
Internationalization is a way to show locale-specific information on a website.It is used to create multilingual language websites.
Below are some major difference between AngularJS and JavaScript Expressions
There are three types of directive scopes available in Angular.
In Angular js $scope is used whenever we have to use dependency injection (D.I) whereas as the scope is used for directive linking.
In One-Way data binding, view (UI part) not updates automatically when data model changed. We need to write custom code to make it updated every time.
ng-bind has one-way data binding.
While in two way binding scope variable will change it’s value every time its data model changed is assigned to a different value.
The $routeProvider is used to configure roots within an AngularJS application. It can be used to link a URL with a corresponding HTML page or template, and a controller (if applicable).
AngularJS was designed to highlight the power of dependency injection, a software design pattern that places an emphasis on giving components their dependencies instead of hardcoding them within the component. For example, if you had a controller that needed to access a list of customers, you would store the actual list of customers in a service that can be injected into the controller instead of hardcoding the list of customers into the code of the controller itself. In AngularJS you can inject values, factories, services, providers, and constants.
In Angular JS $rootscope and $scope both are an object which is used for sharing data from the controller to view
The main difference between $rootscope and $scope is that $rootscope is available globally to across all the controllers whereas $scope is available only in controllers that have created it along with its children controllers.
In Angular js $scope is used whenever we have to use dependency injection (D.I) whereas as the scope is used for directive linking.
Angular js Expression is JavaScript alike code snippets used to bind expression data in view or HTML. Angular expressions are written inside two curly braces.
{{"{"}}{{"{"}}a+b}}Major browsers supported by Angular js
Angular uses these prefixes to prevent accidental code collision with users code. $ prefix is used with public objects whereas $$ prefix is used with a private object.
The transclusion in Angular JS will allow you to move the original children of a directive to a specific location inside a new template.The ng directive marks the insertion point for the transcluded DOM of the very near parent directive that uses transclusion.
ng-transclude or ng-transclude-slot attribute directives are used for transclusion in Angular JS.
There are 30 inbuilt services in AngularJs. Below are few most used services in AngularJs.
To add promise functionality to a service, we inject the “$q” dependency in the service, and then use it like so:
angular.factory('testService', function($q){{"{"}} return {{"{"}} getName: function(){{"{"}} var deferred = $q.defer(); //API call here that returns data testAPI.getName().then(function(name){{"{"}} deferred.resolve(name) }) return deferred.promise; } } })
To reset a timeout
and/or $interval
, assign the result of
the function to a variable and then call the .cancel()
function:
var customTimeout = $timeout(function() {{"{"}}
// arbitrary code
}, 55);
$timeout.cancel(customTimeout);
To disable $watch(), we call its deregistration function. $watch() then returns a deregistration function that we store to a variable and that will be called for cleanup:
var deregisterWatchFn = $scope.$on('$destroy', function() {{"{"}}
// we invoke that deregistration function, to disable the watch
deregisterWatchFn();
});
Is a great pattern that restricts the use of a class more than once. We can find singleton pattern in angular in dependency injection and in the services.
In a sense, if the candidate does 2 times ‘new Object()
‘ without this pattern, the candidate will be alocating 2 pieces of memory
for the same object. With singleton pattern, if the object exists, it'll be reused.
An interceptor is a middleware code where all the $http requests go through.
The interceptor is a factory that are registered in $httpProvider
. There are 2 types of requests that go through the interceptor, request and response (with requestError
and responseError
respectively). This piece of code is very useful
for error handling, authentication or middleware in all the requests/responses.
The developer should use the ngPattern
directive to perform a regex match that matches Twitter usernames. The same principal can be applied to validating phone numbers, serial numbers, barcodes, zip codes and any other text input.
Angular has a built-in error handler service called $exceptionHandler
which can easily be overriden as seen below:
myApp.factory('$exceptionHandler', function($log, ErrorService) {{"{"}}
return function(exception, cause) {{"{"}}
if (console) {{"{"}}
$log.error(exception);
$log.error(cause);
}
ErrorService.send(exception, cause);
};
});
This can be done by using the ng-hide
directive in
conjunction with a controller to hide an HTML element on button click.
<div ng-controller="MyCtrl">
<button ng-click="hide()">Hide element</button>
<p ng-hide="isHide">Hello World!</p>
</div>
function MyCtrl($scope) {{"{"}}
$scope.isHide = false;
$scope.hide = function() {{"{"}}
$scope.isHide = true;
};
}
The developer can use the ng-disabled
directive and bind its condition to the checkbox’s state.
<body ng-app>
<label><input type="checkbox" ng-model="checked"/>Disable Button</label>
<button ng-disabled="checked">Select me</button>
</body>
Angular (2/4/5) is not a programming language like Javascript or Typescript. Angular is a front-end or client-side Framework, which needs a programming language like Typescript (developed by Microsoft). Now, what does it mean when one says, "Angular is a client-side framework"? It means that it runs on the client-side or user's browser and not on a Web Server (where java/python/ruby/vb.net run). Of course, there is the Angular Universal which allows Angular to run on a server; but, primarily, angular is a client-side framework. Angular is a product developed and maintained by the techie giant Google and has adopted the SPA (Single Page Application) principles.
Angular 2 has better powerful templates, event-handling capabilities and better support for mobile devices.
Typescript: − The newer version of Angular is based on Typescript. This is a superset of JavaScript and is maintained by Microsoft.
Components: − The earlier versions of Angular had a focus on Controllers but now have changed the focus to having components over controllers. Components help to build the applications into many modules. This helps in better maintaining the application over a period of time. In this way an application can be easily tested, it reduces the cost to a company.
Services: − Services are a set of code or programs that can be shared by different components of an application. So for example, if you had a data component that picked data from a database,
Service: − This is used to create components which can be shared across the entire application.it is like utility classes.
Modules: − This is used to break up the application into logical pieces of code. Each piece of code or module is designed to perform a single task.
Component: − This can be used to bring the modules together.
Templates: − This is used to define the views of an Angular JS application.
Metadata: − This can be used to add more data to an Angular JS class.
Typescript is a object oriented compiled language. Typescript is a general purpose programming language developed by Microsoft and also a superset of JavaScript programming language. Angular 4 framework is completely built on top of Typescript language. Typescript is a primary language used in Angular which is being treated as a first-class citizen. Typescript can be used to develop Angular apps and the code will be transpiled later using transpilers to support multiple or different versions of browser platforms.
This is the common Angular 2/4/5/6 Interview Questions that are asked in an interview. The Components are defined as the basic classes which interact with the web page components such as html file. The components will be defined as Components using Decorators. Each and every component will be designated with a predefined a template. A component can be defined using @Component which is called as Decorator. The selector, style, and template can be defined inside the component to implement the further functionality.
A Module in Angular is defined as the file where all the Directives, Components, Pipes and Services are grouped and inter linked together to make it a perfect working Angular application. Every Angular app has a root module which will be defined inside app.module.ts which is Typescript file format. To define a module in Angular 4, NgModule can be used.
The Components in Angular 4 are defined as the basic classes which interact with the web page components such as html files or UI elements. The components will be defined as Components using Decorators. Each and every component will be designated with a predefined a template. A Class can be defined using an Angular Directive to make it a Directive which can be used at run time by processing and instantiating.
Routing in the Angular application is the process of applying routes to different components to display the content of the component defined mainly in Single Page Applications. This routing configuration can be defined in the root AppModule. The Router functionality in Angular enables the users to navigate from one task to different other tasks while performing multiple functionalities. A Route is defined as the application by mapping the URL to the different components.
The Directives in Angular 4 can be defined as the extended HTML attributes which can be defined as custom attributes. The Directives in Angular 4 can be pre-defined or can be Custom defined to manipulate the functionality of DOM elements. There are three different kinds of Directives in Angular 4, they are Components, Structural Directives and Attribute Directives. The Components are nothing but directives with a template. The Structural Directive is defined as which changes the DOM structure by adding or removing the DOM elements. The Attribute Directives are defined as a modification in the behavior of a component, or an element or any other directive.
This is the frequently asked Angular 4 Interview Questions in an interview. The Isolated Unit Test is defined as the process of performing tests on a component or class in an isolated way rather than establishing any dependency with other components. It means that testing will be performed based on every individual components and element in isolation. Isolated Unit Tests are useful in testing the Angular Services and Pipes. In the process of developing pipes in Angular which will be transformed into different kinds before being displayed needs careful testing in order to produce efficient data operations between Model and View components.
The Services in Angular is defined as the process of using the code functionality of the other Components in one component. The applications such as data connections those need to be utilised across different components can be achieved by using the Services in Angular 4. The process of presenting the data from Model to View or vice versa is established by using Services. Services are the best of applying the communication across different classes which do not know each other.
The Dependency Injection in Angular 4 is defined as the process of isolating the dependencies and tight coupling across different components. This will hold the dependencies of components in other components. Angular-Dependency Injection is the way of creating the objects which depend on other objects. The instances of other components will be created or injected into another component using Injection feature.
The Angular application is made using the following:
Transpiling is the process of converting the typescript into javascript (using Traceur, a JS compiler). Though typescript is used to write code in the Angular applications, the code is internally transpiled into javascript
ngOnChanges is the life cycle hook that gets executed whenever a change happens to the data that was bound to an input.
Components break up the application into smaller parts; whereas, Directives add behavior to an existing DOM element.
When it comes to the communication of Angular Components, which are in Parent-Child Relationship; we use @Input in Child Component when we are passing data from Parent to Child Component and @Output is used in Child Component to receive an event from Child to Parent Component.
The HTML elements like p (paragraph) or h1 (heading) have some content between the tags. For example, <p>this is a paragraph</p> and <h1>this is a heading</h1>. Now, similar to this, what if we want to have some custom text or content between the angular tags like <app-tax>some tax-related content</app-tax> This will not work the way it worked for HTML elements. Now, in such cases, the <ng-content> tag directive is used.
When we want to route to a component we use router.navigate. Syntax: this.router.navigate([‘/component_name’]);
ViewEncapsulation decides whether the styles defined in a component can affect the entire application or not. There are three ways to do this in Angular:
Emulated: styles from other HTML spread to the component.
Native: styles from other HTML do not spread to the component.
None: styles defined in a component are visible to all components.
Services help us in not repeating the code. With the creation of services, we can use the same code from different components. Here is the command to create a service in angular, ng g service User (a UserService is created when this command is used).
When a component is dependent on another component the dependency is injected/provided during runtime.
Any activity (button click, mouse click, mouse hover, mouse move, etc) of a user on a frontend/web screen is termed as an event. Such events are passed from the view (.HTML) page to a typescript component (.ts).
RouterOutlet is a substitution for templates rendering the components. In other words, it represents or renders the components on a template at a particular location.
The set of brackets when used with an HTML tag, represent data from a component. For example, on a HTML page which has <h1>{{variableName}}</h1>, here the ‘variableName’ is actually typescript (component) data representing its value on the template; i.e., HTML. This entire concept is called String Interpolation.
Data Binding happens between the HTML (template) and typescript (component). Data binding can be done in 3 ways:
OnChange() - OnInit() - DoCheck() - AfterContentInit() - AfterContentChecked() - AfterViewInit() - AfterViewChecked() - OnDestroy().
With the existence of package.json, it will be easy to manage the dependencies of the project. If we are using typescript in the angular project then we can mention the typescript package and version of typescript in package.json.
In traditional web technology, the client requests for a web page (HTML/JSP/asp) and the server sends the resource (or HTML page), and the client again requests for another page and the server responds with another resource. The problem here is a lot of time is consumed in the requesting/responding or due to a lot of reloading. Whereas, in the SPA technology, we maintain only one page (index.HTML) even though the URL keeps on changing.
ngModel is a directive which can be applied on a text field. This a two-way data binding. ngModel is represented by [()]
It is a method which is subscribed to an observable. Whenever the subscribe method is called, an independent execution of the observable happens.
Observables are lazy, which means nothing happens until a subscription is made. Whereas Promises are eager; which means as soon as a promise is created, the execution takes place. Observable is a stream in which passing of zero or more events is possible and the callback is called for each event. Whereas, promise handles a single event.
When an observable or promise returns something, we use a temporary property to hold the content. Later, we bind the same content to the template. With the usage of AsyncPipe, the promise or observable can be directly used in a template and a temporary property is not required.
Authentication: The user login credentials are passed to an authenticate API (on the server). On the server side validation of the credentials happens and a JSON Web Token (JWT) is returned. JWT is a JSON object that has some information or attributes about the current user. Once the JWT is given to the client, the client or the user will be identified with that JWT.
Authorization: After logging in successfully, the authenticated or genuine user does not have access to everything. The user is not authorized to access someone else’s data, he/she is authorized to access some data.
Every angular application gets compiled internally. The angular compiler takes javascript code, compiles it and produces javascript code again. Ahead-of-Time Compilation does not happen every time or for every user, as is the case with Just-In-Time (JIT) Compilation.
It is a library which helps us maintain the state of the application. Redux is not required in applications that are simple with the simple data flow, it is used in Single Page Applications that have complex data flow.
This feature is used to change the output on the template; something like changing the string into uppercase and displaying it on the template. It can also change Date format accordingly.
In ng-Class, loading of CSS class is possible; whereas, in ng-Style we can set the CSS style.
Typescript is a superset of Javascript. Earlier, Javascript was the only client side language supported by all browsers. But, the problem with Javascript is, it is not a pure Object Oriented Programming Language. The code written in JS without following patterns like Prototype Pattern, becomes messy and finally leading to difficulties in maintainability and reusability. Instead of learning concepts (like patterns) to maintain code, programmers prefer to maintain the code in a OOP approach and is made avilable with a programming language like Typescript was thus developed by Microsoft in a way that it can work as Javascript and also offer what javascript cannot ie;
pure OOPS as Typescript offers concepts like Generics, Interfaces and Types (a Static Typed Language) which makes it is easier to catch incorrect data types passing to variables.
TS provides flexibility to programmers experienced in java, .net as it offers encapsulation through classes and interfaces.
JS version ES5 offers features like Constructor Function, Dynamic Types, Prototypes. The next version of Javascript ie ES6 introduced new feature like Class keyword but not supported by many browsers.
TS offers Arrow Functions (=>) which is an ES6 feature not supported by many browsers directly but when used in TS, gets compiled into JS ES5 and runs in any browser.
TS is not the only alternative to JS, we have CoffeScript, Dart(Google).
Finally, it is like, TS makes life easier when compared to JS.
Components are just simple classes which are declared as components with the help of component decorators.
It becomes easy to create an application which already works, with the help of angular CLI commands. “Ng generate” is used to generate components, routes, services, and pipes. Simple test shells are also created with the help of this CLI command. For generating a component in angular4 with the help of CLI command, you need to follow the following syntax-
ng generate component component_name;
The ngIf is a built-in template directive which is used to add or remove some parts of DOM. This addition or removal depends on the expression being true or false.
If the expression is evaluated to false, then the ngIf directive removes the HTML element. If the expression is evaluated to be true, then the element gets added to the DOM.
Syntax- *ngIf=”<condition>”
<ul *ngFor="let person of people"
*ngIf="person.age < 30">
<li>{{person.name}}</li></ul>
AOT stands for Ahead of Time, There is no different compiler used in AOT just the sequence of process is changed. Instead of compiling at runtime in the browser like JIT compilation.
The components and templates are compiled at built time and converted to native JavaScript and html. So the browser does not have compile the application so it can directly render it and save time and system resources.
Advantages:AOT provides build time error detection so many compile type errors are detected before it running the application. Faster download times as the application is compiled and bundled at build time, which eliminates the need of loading the angular compiler and its libraries leading to a lesser runtime. Faster Rendering time as the application is already compiled and only needs to be rendered on the browser.
Disadvantages: Angular version lower than 4 produces large JavaScript bundles after compilation, which defeats the purpose of AOT. It only works only with HTML and CSS, other file types need to be built previously. It needs a clean-up step before compiling.
Angular JS | Angular 2 |
Released by Google in the year 2010. | Released in Sept 2016. |
JavaScript-based framework for creating SPA. | Complete re-write of AngularJS version. |
Still supported but no longer will be developed. | It's updated version regularly released because of Semantic Versioning. |
The architecture of AngularJS is based on MVC. | The architecture of Angular 2 is based on service/controller. |
AngularJS was not developed with a mobile base in mind. | Angular 2 is a mobile-oriented framework. |
AngularJS code can write by using only ES5, ES6, and Dart. | We can use ES5, ES6, Typescript to write an Angular 2 code. |
Based on controllers whose scope is now over. | Nowadays, the controllers are replaced by components, and Angular two is completely component based. |
Factory, service, provider, value and constant are used for services | The class is the only method to define services in Angular2 |
Run on only client-side | Runs on client-side & server-side |
ng-app and angular bootstrap function are used to initialize | bootstrapmodule() function is used to initialize |
Angular 2 | Angular 4 |
The code generated using Angular 2 is bigger, and the file size is also larger. | Angular 4.0 has reduced the bundled file size by 60%. Thus code generated is reduced which helps to accelerate the application performance. |
Angular two is not backward compatible with Angular JS. | Angular four is backward compatible with Angular 2 for most applications. |
There is no specific no proper disapproval phases to adjust codes. | There will be proper disapproval phases to allow developers to adjust their code |
There is no animation feature offers in Angular 2. | Animation features are pulled out of @angular/core and included into their package |
Angular 4 | Angular 5 |
Support for Router ParamMap | New Router Lifecycle Event |
Dynamic Components with NgComponentOutlet | Compiler Improvements |
TypeScript 2.4 with this version that functions as a JavaScript superset that can be used for optional static typing, interfaces, and classes | Angular 5 comes with build optimizer which is a part of the platform's command like a tool. |
HTTP Request Simplified | Optimization with HttpClient Feature |
Includes Animation Package | Internationalized Date & Currency |