Angulr Int
Angulr Int
AngularJS is a javascript framework used for creating single web page applications. It allows
you to use HTML as your template language and enables you to extend HTML’s syntax to
express your application’s components clearly
Scope
Controller
Model
View
Services
Data Binding
Directives
Filters
Testable
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.
In AngularJS services are the singleton objects or functions that are used for carrying out specific
tasks. It holds some business logic and these function can be called as controllers, directive,
filters and so on.
5) Explain what is Angular Expression? Explain what is key difference between angular
expressions and JavaScript expressions?
Like JavaScript, Angular expressions are code snippets that are usually placed in binding such
as {{ expression }}
The key difference between the JavaScript expressions and Angular expressions
Context : In Angular, the expressions are evaluated against a scope object, while the
Javascript expressions are evaluated against the global window
Forgiving: In Angular expression evaluation is forgiving to null and undefined, while in
Javascript undefined properties generates TypeError or ReferenceError
No Control Flow Statements: Loops, conditionals or exceptions cannot be used in an
angular expression
Filters: To format data before displaying it you can use filters
6) With options on page load how you can initialize a select box ?
You can initialize a select box with options on page load by using ng-init directive
7) Explain what are directives ? Mention some of the most commonly used directives in
AngularJS application ?
A directive is something that introduces new syntax, they are like markers on DOM element
which attaches a special behavior to it. In any AngularJS application, directives are the most
important components.
Some of the commonly used directives are ng-model, ng-App, ng-bind, ng-repeat , ng-
show etc.
Angular js routes enable you to create different URLs for different content in your application.
Different URLs for different content enables user to bookmark URLs to specific content. Each
such bookmarkable URL in AngularJS is called a route
A value in Angular JS is a simple object. It can be a number, string or JavaScript object. Values
are typically used as configuration injected into factories, services or controllers. A value should
be belong to an AngularJS module.
Injecting a value into an AngularJS controller function is done by adding a parameter with the
same name as the value
Automatic synchronization of data between the model and view components is referred as data
binding in AngularJS. There are two ways for data binding
1. Data mining in classical template systems
2. Data binding in angular templates
In Angular.js the compiler during the compilation process matches text and attributes using
interpolate service to see if they contains embedded expressions. As part of normal digest cycle
these expressions are updated and registered as watches.
13) Mention the steps for the compilation process of HTML happens?
Using the standard browser API, first the HTML is parsed into DOM
By using the call to the $compile () method, compilation of the DOM is performed. The
method traverses the DOM and matches the directives.
Link the template with scope by calling the linking function returned from the previous
step
14) Explain what is directive and Mention what are the different types of Directive?
During compilation process when specific HTML constructs are encountered a behaviour or
function is triggered, this function is referred as directive. It is executed when the compiler
encounters it in the DOM.
Element directives
Attribute directives
CSS class directives
Comment directives
Pre-linking function: Pre-linking function is executed before the child elements are
linked. It is not considered as the safe way for DOM transformation.
Post linking function: Post linking function is executed after the child elements are
linked. It is safe to do DOM transformation by post-linking function
17) Explain what is the difference between link and compile in Angular.js?
Compile function: It is used for template DOM Manipulation and collect all of the
directives.
Link function: It is used for registering DOM listeners as well as instance DOM
manipulation. It is executed once the template has been cloned.
For creating the directive, factory method is used. It is invoked only once, when compiler
matches the directive for the first time. By using $injector.invoke the factory method is invoked.
19) Mention what are the styling form that ngModel adds to CSS classes ?
ngModel adds these CSS classes to allow styling of form as well as control
ng- valid
ng- invalid
ng-pristine
ng-dirty
DI or Dependency Injection is a software design pattern that deals with how code gets hold of its
dependencies. In order to retrieve elements of the application which is required to be configured
when module gets loaded , the operation “config” uses dependency injection.
These are the ways that object uses to hold of its dependencies
23) Explain the concept of scope hierarchy? How many scope can an application have?
Each angular application consist of one root scope but may have several child scopes. As child
controllers and some directives create new child scopes, application can have multiple scopes.
When new scopes are formed or created they are added as a children of their parent scope.
Similar to DOM, they also creates a hierarchical structure.
AngularJS combines the functionalities of most of the 3rd party libraries, it supports individual
functionalities required to develop HTML5 Apps. While Backbone.js do their jobs individually.
Intially it was developed by Misko Hevery and Adam Abrons. Currently it is beBelow are the list
of Best AngularJS Interview Questions and Answers
1) What is Angular JS ?
AngularJS is a JavaScript framework that is used for making rich, extensible web applications.
It runs on plain JavaScript and HTML, so you don’t need any other dependencies to make it
work.AngularJS is perfect for Single Page Applications (SPA). It is basically used for binding
JavaScript objects with HTML UI elements.
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 scope is the object that represents the “model” of your application. It contains fields that
store data which is presented to the user via the template, as well as functions which can be
called when the user performs certain actions such as clicking a button.
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.
6) Explain Directives in AngularJs ?
AngularJS directives are extended HTML attributes with the ng prefix. The 3 main directives of
angular js are:
ng-app:- directive is used to flag the HTML element that Angular should consider to be
the root element of our application. Angular uses the spinal-case for its custom attributes
and camelCase for the corresponding directives which implement them.
ng-model:- directive allows us to bind values of HTML controls (input, select, textarea)
to application data. When using ngModel, not only change in the scope reflected in the
view, but changes in the view are reflected back into the scope.
ng-bind:- directive binds application modal data to the HTML view.
For testing AngularJS applications there are certain tools that you should use that will
make testing much easier to set up and run.
Karma
Karma is a JavaScript command line tool that can be used to spawn a web server which loads
your application’s source code and executes your tests. You can configure Karma to run against
a number of browsers, which is useful for being confident that your application works on all
browsers you need to support. Karma is executed on the command line and will display the
results of your tests on the command line once they have run in the browser.
Karma is a NodeJS application and should be installed through NPM/YARN. Full installation
instructions are available on the Karma website.
Jasmine
Jasmine is a behavior-driven development framework for JavaScript that has become the most
popular choice for testing AngularJS applications. Jasmine provides functions to help with
structuring your tests and also making assertions. As your tests grow, keeping them well
structured and documented is vital, and Jasmine helps achieve this.
Jasmine comes with a number of matches that help you make a variety of assertions. You should
read the Jasmine documentation to see what they are. To use Jasmine with Karma, we use the
karma-jasmine test runner.
angular-mocks
AngularJS also provides the ngMock module, which provides mocking for your tests. This is
used to inject and mock AngularJS services within unit tests. In addition, it is able to extend
other modules so they are synchronous. Having tests synchronous keeps them much cleaner and
easier to work with. One of the most useful parts of ngMock is $httpBackend, which lets us
mock XHR requests in tests and return sample data instead.
Source:https://docs.angularjs.org/guide/unit-testing
We can share data by creating a service, Services are the easiest, fastest and cleaner way to share
data between controllers in AngularJs.There are also other ways to share data between
controllers, they are
Using Events
$parent, nextSibling, controllerAs
Using the $rootScope
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.
Below are some major difference between AngularJS and JavaScript Expressions
Create an angular.module
Assign a controller to the module
Link your module to HTML with ng-app
Link the controller to HTML with ng-controller directive
Angular Modules are place where we write code of our Angular application.Writing Modules
makes our code more maintainable, testable, and readable. All dependencies for our app are
defined in modules.
You can isolate a directive’s Scope by passing an object to the scope option of directive.
This tells the directive to keep scope inside of itself and not to inherit or share with other scopes.
16) What is the difference between one-way binding and two-way binding in AngularJS ?
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.
17) How would you make an AngularJS service return a promise? Write a code snippet as
an example
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();
return deferred.promise;
}
}
})
The $q library is a helper provider that implements promises and deferred objects to enable
asynchronous functionality
Source: https://docs.angularjs.org/api/ng/service/$q
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).
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}}
angular.module('myApp', [])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl : 'partials/home.html',
controller : mainController
})
Angular js supports all standard HTML5 attributes to validate input. Below are few built-in
validators in Angular js.
required
min
max
type=”number” OR type=”email”
27) What is AngularJS prefixes $ and $$?
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.
28) What are directives? How to create and use custom Directive in AngularJS .
In angular there is a scope variable called $parent (i.e. $scope.$parent). $parent is used to access
parent scope from child controller in Angular JS.
Example:
<div ng-controller="ParentCtrl">
<h1>{{ name }}</h1>
<p>{{ address }}</p>
<div ng-controller="ChildCtrl">
<h1>{{ title }}</h1>
<input type="text" ng-model="$parent.address" />
</div>
Angular form validation and ng-pattern directive can be used to validate the email and phone
number in Angular JS.
Compile function: To template DOM manipulation and to gather all the directives, the compile
function is used.
Link function: To register DOM listeners as well as for the instance DOM manipulation, the
Link function is used.
32) How can you get URL parameters from AngularJS Controller?
The RouteProvider and the RouteParams can be used to get the URL parameters in the
controller.
As the route wires up the URL to the controller and RouteParams can be passed to the controller
to get the URL parameters.
Caching can be enabled by setting the config.cache value or the default cache value to TRUE or
to a cache object that is created with $cacheFactory.
In case you want to cache all the responses, then you can set the default cache value to TRUE.
And, if you want to cache a specific response, then you can set the config.cache value to TRUE.
34) Explain the use of Ng-If, Ng-Switch, And Ng-Repeat directives in AngularJS ?
ng-if – This directive removes a portion of the DOM tree, which is based on the expression.
In case the expression is assigned to ng-if, it evaluates to a false value, and then the element is
deleted from the DOM tree, or else a clone of the element is reinserted into the DOM.
ng-switch – This directive is used based on a scope expression to conditionally swap DOM
structure on the template.
The ng-switch default directive will be preserved at the specific location in a template.
ng-repeat – This directive is used to instantiate the template once per item from a collection.
Each template which is instantiated gets its own scope where the given loop variable is set to the
current collection of item.
35) How to change start and end symbols used for AngularJS expressions?
Passing the $interpolateprovider in the config can help us change the start and end symbols used
in our Angular JS expressions.
AngularJS Angular 2
Angular js or Angular 1.x is based Angular 2 is based on service/ components
on MVC Architecture
Javascript is used to write Typescript (a superset of javascript) is used to
applications in Angular js. write an application in Angular2.
A controller is used to writing In Angular 2 Controllers are totally eliminated
logic and interact with Model and and Components take its place.
view.
Angular 1 is created for In Angular 2 can be used for developing native
developing Single page web- applications for a mobile platform like React
applications. Native as well as interactive
web applications.
Angularjs is easy to set up, you Angular 2 is dependent on other modules/
just need to include the angular.js package. It gives little brainstorm to install and
library to start. run Angular 2.
In Angularjs ng-app directive is ng-app is removed in Angular 2. You need to
used bootstrap the app. call Angular2 bootstrap method to bootstrap
your application.
Adding the regex directly to the ng pattern to the attribute can help you validate the URL in
Angular JS.
locale service provides with the localization rules for Angular JS components.
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.
A stateful component is a detail implementation of the component that can change over time
and the stateful components can have stateless components inside them, while the stateless
components are a plain JavaScript function.
GET
HEAD
POST
PUT
DELETE
CONNECT
OPTIONS
TRACE
The track by is used with ng-repeat and describes to AngularJS how it tracks the association
between the DOM and the Model. It improves the rendering performance.
$templateCache is a Cache object that is created by the $cache factory. The first time you use a
template, it is loaded in the $templateCache for easy and quick retrieval.
45) What is the difference between a unit and end-to-end (e2e) test in AngularJS ?
The unit testing is a method that helps the developers validate the isolated pieces of code and
end-to-end testing is required when you want to ascertain the set of components integrated
together work as you expect.
46) Explain .config() and .run() methods in AngularJS ?
.config() – The .config() function is used to add configuration blocks on the module.
.run() - The .run() function is used to add run blocks on the module.
It is the most common type of dependency on AngularJS application. A service can be mocked
in two ways by either getting an instance of actual service using an inject block or by
implementing a mock service using $provide.
The caching is implemented by using a cache object that stores and retrieves data and is
primarily used by $templaterequest and script directive to cache the templates.
Compile – It compiles an HTML DOM into a template and produces a template function that is
used to link scope and template together. It is executed only once.
There are two ways to use a Multiple ng-app within a single page in AngularJS. One is the
bootstrap method and the other is ngModules directive.
52) How to set focus on the input field in Angular 1.x?
Define a directive, use that directive on the element we are targeting and have it $watch a
trigger/property to know when to focus the element.
The $http.post method is used to send an http post request in AngularJS. The method has three
parameters namely URL, data, config.
The $scope is an object with the available methods and properties. It is used to get all controls on
the controller.JS files. It is available for both the controller and the view. "This" is the controller
used when the controller’s constructor function is called.
$Location is used when you don't want the full page to reload when the URL is changed and
the window.location is used when you want to change the URL, reload the page or navigate to a
different page.
It is used to prevent the Angular HTML template from getting displayed briefly by the browser
in its uncompiled form while the application is still loading. It is used to avoid the undesirable
flicker effect caused by HTML template display.
The AngularJS provides a date filter through which you can format the date into the required
form.
Syntax
{{ today | date:'MM/dd/yyyy'}}
$broadcast, $emit, and $on are services in Angular Js. Below we have listed why they are used In
Angular JS.
$broadcast(): $broadcast() service of Angular is used to propagate the event to all of his child
controllers and it’s registered parent $rootscope.scope listeners.
$rootScope.$broadcast('SummaryEvent', {
priority: priority
});
$on(): AngularJS $on() service is used to listen any type of event raised by $broadcast and
$emit.
Scopeless controllers have no $scope injected and the functions and properties are binded
directly onto the controller. Scopeless controllers are used in the situation where the controller
becomes complex by using the $scope to provide data.
62) What is Isolate Scope in AngularJS and why it is required?
It is a scope that exists separately with no prototypal inheritance. It makes the components
reusable and permits to control the binding either one-way or two-way.
$evalAsync executes the expression on the current scope at a later time and makes no guarantees
as to when the expression will be executed.
$timeout also executes the expression on the current scope on later time but also runs after the
DOM has been manipulated by the Angular and after the browser renders that cause flicker in
some cases.
In order to disable the right click event in AngularJS, you need to add the disable-right-click as
the element’s attribute. Simply use preventDefault(), this cancels the event and stops further
propagation of the event.
The provider in AngularJS is used to internally create a factory, services etc., during the phase of
configuration. The provider is the special factory method which is used to return the
service/value/factory.
After reading the HTML which is there within the root, Angular compiles it all into an internal
representation. This process of reading and compiling is called as the bootstrapping process.
When the code is written instead of the use of the ng-app directive, manual bootstrapping is
done. It is actually the functional component that is there in the Core ng module which is actually
used so that the user can start up an application hosted by Angular manually. Thereby it provides
more control over the beginning of the application.
69) What is a dynamic route in AngularJS and how do you implement it?
A dynamic route is a typical approach to server communication is using the HTTP server. In
order to implement it, firstly write a config function that uses $http and $routeprovider to gather
all information on available routes.
The ng routing is deep linking services and directives for angular applications whereas the UI
routing is a 3rd party module routing and is very powerful. It does everything an ng router does
as well as has many other extra functions.
Routing is one the core feature of AngularJs Framework that is useful in building a single page
web application with multiple views. In Angular ngRoute Module is used to implement
Routing. ngView,$routeProvider,$route and $routeParams are different components of
the ngRoute Module that helps to configure and mapping Url to views.
73) Explain Event in AngularJS , List some events you have worked in AngularJs?
The AngularJS framework includes certain directives that can be used to provide the custom
behavior on various DOM events. Some of the events are:
ng-click
ng-keyup
ng-keydown
ng-keypress
ng-dblclick
ng-mousedown
ng-mouseleave
ng-mouseenter
ng-change
The service in AngularJS is created by registering it with the module it is going to operate in.
There are three ways to create the angular service. They are:
Factory
Service
Provider
The HTML pages can be embedded within an HTML page using the ng-include directive.
In order to hide/show the div in AngularJS just get rid of display: none, the rest is in the control.
If you want to hide it by default then set the value of scope.myvalue to false.
78) How to create a service using Factory in AngularJS ?
Creating a service using the module's factory API is one of the most common ways to create a
service. We first create an object, add properties to it and return the same object, which can later
be injected into the components like service, controller, filter or directive.
There are 30 inbuilt services in AngularJs. Below are few most used services in AngularJs.
$location
$scope
$http
$timeout
$interval
$window
Angualr.JS filters are efficient in modifying the data. With the help of pipe (|) character, they are
clubbed into the directive or expression.
Filters Functions
Uppercase It used to convert text to upper case text.
Lowercas It used to convert text to lower case text.
e
Currency It is used to formats a number to a currency format.
Order by It is used to orders the array on the basis of given criteria.
Filter It is used to order the array to a subset of it on the basis of given
criteria.
Just be imaginative, the devices that access your server but they are disabled for
JavaScript. So the users are unable to access your web apps or website. In the case of a
great number of users, AngularJS based web is not so efficient. In spite of this, it is good
for plain HTML-based web.
If you are a developer and want to do some traditional with almost zilch knowledge of
MVC then you are not advised to use the Angular.JS because it will be time-consuming
for you. You should hire an expert who has good knowledge of MVC if you are short in
time to submit the project
If you are fresh in Angular.JS then it will be difficult for you to deal with complex
entities such as Quite layered and hierarchically and scopes. Debugging the scope is
believed a very hard task for many programmers.
There are several features of Angular.JS like directives, dependency injection and
factories which are hard to use. So, you have to spend a lot of time on it to understand all
of them or prefer to hire an expert.
The browser on old computers and mobile are failed or take a little more time to render
pages of application and websites designed using the framework. It happens because the
browser begins to complete some supplementary tasks like DOM manipulation. But this
quibble does not seem in the new devices.
Difficult to learn
It is very hard to accustom to the framework. Plus, you may get some additional
problems like limited documentation. But Angular.JS continuously make it easier
DDO Stands for Directive Definition Object. DDO is used while creating a custom directive in
AngularJs.
83) What is an interceptor in Angular? Why it is used?
An interceptor is a middleware code in AngularJs where all the $http requests go through. It is
attached with $httpProvider service and able to intercept request and response objects.
Interceptor Middleware is useful for error handling, authentication and other filters you want to
apply on request and response.
It is used to allocating the value of an object into another object however the object value must
not be altered.
If you are adding any new property or altering any value of the property then the object noting to
the same object will update by applying angular. Copy() method.
85) Which filter will be executed one or more times during the each $Digest cycle?
$stateful filters are executed one or more times during each $Digest cycle. It is not
recommended to write a $stateful filter in AngularJS.
Recommended Language:
Language Recommended Language: JavaScript
TypeScript
Expression Specific ng directive is required for Uses () to bind an event and [] for
Syntax the image/property and an event property binding
Mobile Support Doesn’t provide any mobile support Provides mobile support
2. What is Angular?
Angular is an open-source front-end web framework. It is one of the most popular JavaScript
frameworks that is mainly maintained by Google. It provides a platform for easy development of
web-based applications and empowers the front end developers in curating cross-platform
applications. It integrates powerful features like declarative templates, an end to end tooling,
dependency injection and various other best practices that smoothens the development path.
Angular expressions are code snippets that are usually placed in binding such
as {{ expression }} similar to JavaScript. These expressions are used to bind application data to
HTML
Syntax: {{ expression }}
Instructor-led Sessions
Assignments
Assessments
Lifetime Access
Explore Curriculum
Annotations in angular are “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 that are used for separating decoration or modification of a class without actually
altering the original source code.
1. Component Directives
2. Structural Directives
3. Attribute Directives
a. String Interpolation
b. Property Binding
c. Event Binding
d. Two-Way Data Binding
17. How can you differentiate between Angular expressions and JavaScript expressions?
Angular Expressions JavaScript Expressions
1. They can contain literals, operators, and 1. They can contain literals, operators, and
variables. variables.
2. They can be written inside the HTML tags. 2. They can’t be written inside the HTML tags.
3. They do not support conditionals, loops, 3. They do support conditionals, loops, and
and exceptions. exceptions.
18. List at down the ways in which you can communicate between applications modules
using core Angular functionality.
Below are the most general ways for communicating between application modules using core
Angular functionality :
Using events
Using services
By assigning models on $rootScope
Directly between controllers [$parent, $$childHead, $$nextSibling, etc.]
Directly between controllers [ControllerAs, or other forms of inheritance]
$scope in Angular is used for implementing the concept of dependency injection (D.I) on
the other hand scope is used for directive linking.
$scope is the service provided by $scopeProviderwhich can be injected into controllers,
directives or other services whereas Scope can be anything such as a function parameter
name, etc.
21. Explain the concept of scope hierarchy?
The $scope objects in Angular are organized into a hierarchy and are majorly used by views. It
contains a root scope which can further contain scopes known as child scopes. One root scope
can contain more than one child scopes. Here each view has its own $scope thus the variables set
by its view controller will remain hidden to the other controllers. The Scope hierarchy generally
looks like:
Root $scope
o $scope for Controller 1
o $scope for Controller 2
o ..
o $scope for Controller ‘n’
22. What is AOT?
AOT stands for Angular Ahead-of-Time compiler. It is used for pre-compiling the application
components and along with their templates during the build process. Angular applications which
are compiled with AOT has a smaller launching time. Also, components of these applications
can execute immediately, without needing any client-side compilation. Templates in these
applications are embedded as code within their components. It reduces the need for downloading
the Angular compiler which saves you from a cumbersome task. AOT compiler can discard the
unused directives which are further thrown out using a tree-shaking tool.
Whereas, in Two-way data binding, the View or the UI part is updated implicitly as soon as the
data model changes. It is a synchronization process, unlike One-way data binding.
JQUERY UI DEVELOPMENT
jQuery UI Development
Reviews
5(791)
Next
1. Stands for Document Object Model 1. Stands for Browser Object Model
5. W3C Recommended standard specifications 5. Each browser has its own implementation
ng-click
ng-copy
ng-cut
ng-dblclick
ng-keydown
ng-keypress
ng-keyup
ng-mousedown
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
ng-mouseup
ng-blur
1. Karma
2. Angular Mocks
3. Mocha
4. Browserify
5. Sion
Factory
Service
Provider
Automatic Bootstrapping: this is done by adding the ng-app directive to the root of the
application, typically on the tag or tag if you want angular to bootstrap your application
automatically. When Angular finds ng-app directive, it loads the module associated with
it and then compiles the DOM.
Manual Bootstrapping: Manual bootstrapping provides you more control on how and
when to initialize your Angular application. It is useful where you want to perform any
other operation before Angular wakes up and compile the page.
Compile function is used for template DOM Manipulation and to collect all the
directives.
Link function is used for registering DOM listeners as well as instance DOM
manipulation and is executed once the template has been cloned.
In Angular, constants are similar to the services which are used to define the global data.
Constants are declared using the keyword “constant”. They are created using constant
dependency and can be injected anywhere in controller or services.
44. What is the difference between a provider, a service and a factory in Angular?
Provider Service Factory
Comparing objects
Iterating objects
Converting data
To set Cookies – For setting the cookies in a key-value format ‘put’ method is used.
cookie.set('nameOfCookie',"cookieValue");
To get Cookies – For retrieving the cookies ‘get’ method is used.
cookie.get(‘nameOfCookie’);
To clear Cookies – For removing cookies ‘remove’ method is used.
cookie.delete(‘nameOfCookie’);
47. If your data model is updated outside the ‘Zone’, explain the process how will you the
view?
You can update your view using any of the following:
Example
<div ng-app=“myApp” ng-controller=“myCtrl”>
First Name :
<input type=“text” ng-model=“firstName”>
<br />
Last Name :
<input type=“text” ng-model=“lastName”>
<br>
Full Name: {{firstName + ” ” + lastName }}
</div>
49. What is the process of inserting an embedded view from a prepared TemplateRef?
@Component({
selector: 'app-root',
template: `
<ng-template #template let-name='fromContext'><div>{{name}}</ng-template>
`
})
export class AppComponent implements AfterViewChecked {
@ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
constructor() { }
ngAfterViewChecked() {
this.vc.createEmbeddedView(this._template, {fromContext: 'John'});
}
}
50. How can you hide an HTML element just by a button click in angular?
An HTML element can be easily hidden using the ng-hide directive in conjunction along with a
controller to hide an HTML element on button click.
View
<div ng-controller="MyController">
<button ng-click="hide()">Hide element</button>
<p ng-hide="isHide">Hello World!</p>
</div>
Controller
controller: function() {
this.isHide = false;
this.hide = function(){
this.isHide = true; }; }
Q #10) Explain the differences between one-way binding and two-way binding.
Answer: One-way binding is used to bind the data from the model to view without updating the
HTML template or view automatically.
Thus in order to update the HTML template, we need to write a custom code which will update
the view every time whenever a data is binded from model to view.
Whereas, two-way binding is used to bind the data from the model to view and vice versa(i.e
view to model) by automatically updating the HTML template without writing any custom code.
ng-bind-html: It is a directive which binds the content to the HTML element(view) in a secure
way. $sanitize service is used to sanitize the content to bind into an HTML element. To do this
‘angular-sanitize.js’ must be included in our application.
Syntax to write this,
<ANY ELEMENT ng-bind-html=" expression "> </ANY ELEMENT>
Ng-non-bindable: It specifies AngularJs to not compile the content of this HTML element and
its child nodes.
<ANY ELEMENT ng-non-bindable > </ANY ELEMENT>
Syntax:
module.factory(‘factoryName', function);
<td>{{stu.name}} </td>
</tr>
</table>
A controller cannot be used to share code or state across controllers, but instead of that Angular
service can be used.
</Any>
</div>
Example:
<div ng-app="">
</div>
<element ng-switch-when="value"></element>
...
</ANY_HTML_ELEMENT>
By default, the included file must be located on the same domain as the document.
<div ng-include="'myFile.htm'"></div>
ng-click can be used in scenarios like when you click on a button or when you want to do any
operation. It tells AngularJS what to do when an HTML element is clicked.
Example:
<button ng-click="count = count + 1" ng-init="count=0">OK</button>
The above code will increase the count variable by one whenever the button is clicked.
Syntax:
serviceApp.provider("logService", function ())
<p>
</p>
<p>
</p>
<p>
{{ mySwitch }}
</p>
</div>
Q #36) What are the attributes that can be used during the creation of a new AngularJs
directives?
Answer: There are several attributes which can be used during a new directive creation.
They include:
1. Template: It describes an inline template as a string.
2. Template URL: This attribute specifies the AngularJs HTML compiler to replace the
custom directive inside a template with the HTML content located inside a separate file.
3. Replace: It replaces the current element if the condition is true, if false append this
directive to the current element.
4. Transclude: It allows you to move the original children of a directive to a location inside
the new template.
5. Scope: It creates a new scope for this directive rather than inheriting the parent scope.
6. Controller: It creates a controller which publishes an API for communicating across the
directives.
7. Require: It requires another directive to be present to function the current directive
efficiently.
8. Link: It modifies resulting DOM element instances, adds event listeners, and set up data
binding.
9. Compile: It modifies the DOM template for features across copies of a directive, as when
used in other directives. Your compile function can also return link functions to modify
the resulting element instances.
Q #37) Is Nested Controllers possible or not in AngularJs?
Answer: Yes, it is possible as Nested Controllers are well-defined in a classified manner while
using a view.
Q 38) Is AngularJS well-suited with all browsers?
Answer: Yes, it is companionable with all browsers like Safari, Chrome, Mozilla, Opera, IE etc.
as well as Mobile browsers.
Q 39) Define services in AngularJS.
Answer: AngularJS services are the singleton objects or functions which are used for carrying
out definite tasks.
It embraces some corporate ideas and these purposes can be called as controllers, directive,
filters and so on.
ng-show directive is used to show the HTML element if the expression becomes true. And if the
expression becomes false then the HTML element will be hidden.
Syntax
<element ng-show=”expression”></element>
ng-hide directive is used to hide the HTML element if the expression becomes false.
Syntax
<element ng-hide=”expression”></element>
AngularJS is a framework to build large scale and high performance web application while
keeping them as easy-to-maintain. Following are the features of AngularJS framework.
AngularJS is a powerful JavaScript based development framework to create RICH
Internet Application (RIA).
AngularJS provides developers options to write client side application (using JavaScript)
in a clean MVC (Model View Controller) way.
Application written in AngularJS is cross-browser compliant. AngularJS automatically
handles JavaScript code suitable for each browser.
AngularJS is open source, completely free, and used by thousands of developers around
the world. It is licensed under the Apache License version 2.0.
What is data binding in AngularJS?
Data binding is the automatic synchronization of data between model and view components. ng-
model directive is used in data binding.
What is scope in AngularJS?
Scopes are objects that refer to the model. They act as glue between controller and view.
What are the controllers in AngularJS?
Controllers are JavaScript functions that are bound to a particular scope. They are the prime
actors in AngularJS framework and carry functions to operate on data and decide which view is
to be updated to show the updated model based data.
What are the services in AngularJS?
AngularJS come with several built-in services. For example $https: service is used to make
XMLHttpRequests (Ajax calls). Services are singleton objects which are instantiated only once
in app.
What are the filters in AngularJS?
Filters select a subset of items from an array and return a new array. Filters are used to show
filtered items from a list of items based on defined criteria.
Explain directives in AngularJS.
Directives are markers on DOM elements (such as elements, attributes, css, and more). These
can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has
built-in directives (ng-bind, ng-model, etc) to perform most of the task that developers have to
do.
Explain templates in AngularJS.
Templates are the rendered view with information from the controller and model. These can be
a single file (like index.html) or multiple views in one page using "partials".
What is routing in AngularJS?
It is concept of switching views. AngularJS based controller decides which view to render based
on the business logic.
What is deep linking in AngularJS?
Deep linking allows you to encode the state of application in the URL so that it can be
bookmarked. The application can then be restored from the URL to the same state.
What are the advantages of AngularJS?
Following are the advantages of AngularJS.
AngularJS provides capability to create Single Page Application in a very clean and
maintainable way.
AngularJS provides data binding capability to HTML thus giving user a rich and
responsive experience.
AngularJS code is unit testable.
AngularJS uses dependency injection and make use of separation of concerns.
AngularJS provides reusable components.
With AngularJS, developer writes less code and gets more functionality.
In AngularJS, views are pure html pages, and controllers written in JavaScript do the
business processing.
AngularJS applications can run on all major browsers and smart phones including
Android and iOS based phones/tablets.
What are the disadvantages of AngularJS?
Following are the disadvantages of AngularJS.
Not Secure − Being JavaScript only framework, application written in AngularJS are not
safe. Server side authentication and authorization is must to keep an application secure.
Not degradable − If your application user disables JavaScript then user will just see the
basic page and nothing more.
Which are the core directives of AngularJS?
Following are the three core directives of AngularJS.
ng-app − This directive defines and links an AngularJS application to HTML.
ng-model − This directive binds the values of AngularJS application data to HTML
input controls.
ng-bind − This directive binds the AngularJS Application data to HTML tags.
Explain AngularJS boot process.
When the page is loaded in the browser, following things happen:
HTML document is loaded into the browser, and evaluated by the browser. AngularJS
JavaScript file is loaded; the angular global object is created. Next, JavaScript which
registers controller functions is executed.
Next AngularJS scans through the HTML to look for AngularJS apps and views. Once
view is located, it connects that view to the corresponding controller function.
Next, AngularJS executes the controller functions. It then renders the views with data
from the model populated by the controller. The page gets ready.
What is MVC?
Model View Controller or MVC as it is popularly called, is a software design pattern for
developing web applications. A Model View Controller pattern is made up of the following
three parts:
Model − It is the lowest level of the pattern responsible for maintaining data.
View − It is responsible for displaying all or a portion of the data to the user.
Controller − It is a software Code that controls the interactions between the Model and
View.
Explain ng-app directive.
ng-app directive defines and links an AngularJS application to HTML. It also indicate the start
of the application.
Explain ng-model directive.
ng-model directive binds the values of AngularJS application data to HTML input controls. It
creates a model variable which can be used with the html page and within the container control(
for example, div) having ng-app directive.
Explain ng-bind directive.
ng-bind directive binds the AngularJS Application data to HTML tags. ng-bind updates the
model created by ng-model directive to be displayed in the html tag whenever user input
something in the control or updates the html control's data when model data is updated by
controller.
Explain ng-controller directive.
ng-controller directive tells AngularJS what controller to use with this view. AngularJS
application mainly relies on controllers to control the flow of data in the application. A
controller is a JavaScript object containing attributes/properties and functions. Each controller
accepts $scope as a parameter which refers to the application/module that controller is to
control.
How AngularJS integrates with HTML?
AngularJS being a pure javaScript based library integrates easily with HTML.
Step 1 − Include angularjs javascript libray in the html page
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
Step 2 − Point to AngularJS app
Next we tell what part of the HTML contains the AngularJS app. This done by adding the ng-
app attribute to the root HTML element of the AngularJS app. You can either add it
to html element or body element as shown below:
<body ng-app = "myapp">
</body>
Explain ng-init directive.
ng-init directive initializes an AngularJS Application data. It is used to put values to the
variables to be used in the application.
Explain ng-repeat directive.
ng-repeat directive repeats html elements for each item in a collection.
What are AngularJS expressions?
Expressions are used to bind application data to html. Expressions are written inside double
braces like {{ expression}}. Expressions behave in same way as ng-bind directives. AngularJS
application expressions are pure JavaScript expressions and outputs the data where they are
used.
Explain uppercase filter.
Uppercase filter converts a text to upper case text.
In below example, we've added uppercase filter to an expression using pipe character. Here
we've added uppercase filter to print student name in all capital letters.
Enter first name:<input type = "text" ng-model = "student.firstName">
Enter last name: <input type = "text" ng-model = "student.lastName">
Name in Upper Case: {{student.fullName() | uppercase}}
Explain lowercase filter.
Lowercase filter converts a text to lower case text.
In below example, we've added lowercase filter to an expression using pipe character. Here
we've added lowercase filter to print student name in all lowercase letters.
Enter first name:<input type = "text" ng-model = "student.firstName">
Enter last name: <input type = "text" ng-model = "student.lastName">
Name in Upper Case: {{student.fullName() | lowercase}}
Explain currency filter.
Currency filter formats text in a currency format.
In below example, we've added currency filter to an expression returning number using pipe
character. Here we've added currency filter to print fees using currency format.
Enter fees: <input type = "text" ng-model = "student.fees">
fees: {{student.fees | currency}}
Explain filter filter.
filter filter is used to filter the array to a subset of it based on provided criteria.
In below example, to display only required subjects, we've used subjectName as filter.
Enter subject: <input type = "text" ng-model = "subjectName">
Subject:
<ul>
<li ng-repeat = "subject in student.subjects | filter: subjectName">
{{ subject.name + ', marks:' + subject.marks }}
</li>
</ul>
Explain orderby filter.
orderby filter orders the array based on provided criteria.
In below example, to order subjects by marks, we've used orderBy marks.
Subject:
<ul>
<li ng-repeat = "subject in student.subjects | orderBy:'marks'">
{{ subject.name + ', marks:' + subject.marks }}
</li>
</ul>
Explain ng-disabled directive.
ng-disabled directive disables a given control.
In below example, we've added ng-disabled attribute to a HTML button and pass it a model.
Then we've attached the model to an checkbox and can see the variation.
<input type = "checkbox" ng-model = "enableDisableButton">Disable Button
<button ng-disabled = "enableDisableButton">Click Me!</button>
Explain ng-show directive.
ng-show directive shows a given control.
In below example, we've added ng-show attribute to a HTML button and pass it a model. Then
we've attached the model to a checkbox and can see the variation.
<input type = "checkbox" ng-model = "showHide1">Show Button
<button ng-show = "showHide1">Click Me!</button>
Explain ng-hide directive.
ng-hide directive hides a given control.
In below example, we've added ng-hide attribute to a HTML button and pass it a model. Then
we've attached the model to a checkbox and can see the variation.
<input type = "checkbox" ng-model = "showHide2">Hide Button
<button ng-hide = "showHide2">Click Me!</button>
Explain ng-click directive.
ng-click directive represents a AngularJS click event.
In below example, we've added ng-click attribute to a HTML button and added an expression to
updated a model. Then we can see the variation.
<p>Total click: {{ clickCounter }}</p></td>
<button ng-click = "clickCounter = clickCounter + 1">Click Me!</button>
l
How angular.module works?
angular.module is used to create AngularJS modules along with its dependent modules.
Consider the following example:
var mainApp = angular.module("mainApp", []);
Here we've declared an application mainApp module using angular.module function. We've
passed an empty array to it. This array generally contains dependent modules declared earlier.
How to validate data in AngularJS?
AngularJS enriches form filling and validation. We can use $dirty and $invalid flags to do the
validations in seamless way. Use novalidate with a form declaration to disable any browser
specific validation.
Following can be used to track error.
$dirty − states that value has been changed.
$invalid − states that value entered is invalid.
$error − states the exact error.
Explain ng-include directive.
Using AngularJS, we can embed HTML pages within a HTML page using ng-include directive.
<div ng-app = "" ng-controller = "studentController">
<div ng-include = "'main.htm'"></div>
<div ng-include = "'subjects.htm'"></div>
</div>
How to make an ajax call using Angular JS?
AngularJS provides $https: control which works as a service to make ajax call to read data from
the server. The server makes a database call to get the desired records. AngularJS needs data in
JSON format. Once the data is ready, $https: can be used to get the data from server in the
following manner:
function studentController($scope,$https:) {
var url = "data.txt";
$https:.get(url).success( function(response) {
$scope.students = response;
});
}
What is use of $routeProvider in AngularJS?
$routeProvider is the key service which set the configuration of urls, maps them with the
corresponding html page or ng-template, and attaches a controller with the same.
What is $rootScope?
Scope is a special JavaScript object which plays the role of joining controller with the views.
Scope contains the model data. In controllers, model data is accessed via $scope object.
$rootScope is the parent of all of the scope variables.
What is scope hierarchy in AngularJS?
Scopes are controllers specific. If we define nested controllers then child controller will inherit
the scope of its parent controller.
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller("shapeController", function($scope) {
$scope.message = "In shape controller";
$scope.type = "Shape";
});
mainApp.controller("circleController", function($scope) {
$scope.message = "In circle controller";
});
</script>
Following are the important points to be considered in above example.
We've set values to models in shapeController.
We've overridden message in child controller circleController. When "message" is used
within module of controller circleController, the overridden message will be used.
What is a service?
Services are JavaScript functions and are responsible to do specific tasks only. Each service is
responsible for a specific task for example, $https: is used to make ajax call to get the server
data. $route is used to define the routing information and so on. Inbuilt services are always
prefixed with $ symbol.
What is service method?
Using service method, we define a service and then assign method to it. We've also injected an
already available service to it.
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
What is factory method?
Using factory method, we first define a factory and then assign method to it.
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b
}
return factory;
});
What are the differences between service and factory methods?
factory method is used to define a factory which can later be used to create services as and when
required whereas service method is used to create a service whose purpose is to do some
defined task.
Which components can be injected as a dependency in AngularJS?
AngularJS provides a supreme Dependency Injection mechanism. It provides following core
components which can be injected into each other as dependencies.
value
factory
service
provider
constant
What is provider?
provider is used by AngularJS internally to create services, factory etc. during config
phase(phase during which AngularJS bootstraps itself). Below mention script can be used to
create MathService that we've created earlier. Provider is a special factory method with a
method get() which is used to return the value/service/factory.
//define a module
var mainApp = angular.module("mainApp", []);
...
//create a service using provider which defines a method square to return square of a number.
mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};
factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});
What is constant?
constants are used to pass values at config phase considering the fact that value cannot be used
to be passed during config phase.
mainApp.constant("configParam", "constant value");
Is AngularJS extensible?
Yes! In AngularJS we can create custom directive to extend AngularJS existing functionalities.
Custom directives are used in AngularJS to extend the functionality of HTML. Custom
directives are defined using "directive" function. A custom directive simply replaces the
element for which it is activated. AngularJS application during bootstrap finds the matching
elements and do one time activity using its compile() method of the custom directive then
process the element using link() method of the custom directive based on the scope of the
directive.
On which types of component can we create a custom directive?
AngularJS provides support to create custom directives for following type of elements.
Element directives − Directive activates when a matching element is encountered.
Attribute − Directive activates when a matching attribute is encountered.
CSS − Directive activates when a matching css style is encountered.
Comment − Directive activates when a matching comment is encountered.
What is internationalization?
Internationalization is a way to show locale specific information on a website. For example,
display content of a website in English language in United States and in Danish in France.
How to implement internationalization in AngularJS?
AngularJS supports inbuilt internationalization for three types of filters currency, date and
numbers. We only need to incorporate corresponding js according to locale of the country. By
default it handles the locale of the browser. For example, to use Danish locale, use following
script
<script src = "https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"></script>
1. What is the syntax of ForEach loop? which loop would you use to parse a JSON and
why?
Below is the syntax of for each loop:
angular.ForEach(students,function(value,key)
{
//some code
}
To parse JSON, we can use any loop, but I would use for each loop because it will minimize my
code by eliminating the need to store the length of a JSON in a variable.
A $scope can be considered as a model, whereas the functions written in angular controller
modifies the $scope and HTML display the value of the scope variable.
5. What is $scope?
$scope is a model for a controller and helps the controller in interacting with the view.
(This is a super short answer to this question, but it is complete in every sense. Try not to put any
additional angular terms).
{{nameOfStudent|uppercase}}
Below is the code to count the number of elements in the string by using filter:
angular.module('myCountFilterApp', [])
.filter('count',function()
{
return(function(input)
{
var out=[];
out=input.split(',');
return out.length;
})
});
In the above example, if the string is "21, 34, 45" then output after applying filter will be 3.
Here is some more information on custom filters.
8. What is the difference between ng-if and ng-show?
Ng-if doesn’t render the portion of DOM element on which it is associated if the specified
condition is not met whereas ng-show renders the DOM element but set its CSS property of
display to none if the specified condition is not met.
$http({
method: "POST",
url: "URL",
data: JSON.stringify(value),
type: 'POST',
contentType: 'application/json; charset=utf-8'
}).then(function (response)
{
// success action
});
12. Where should one use form action instead of $http for accessing a method on a server?
Form action should be used at a place where the server-side method takes the control to some
other view in other word leads to redirection whereas HTTP request should be used where the
server method returns some data.
13. What is the purpose of find index in AngularJS and what does it return if no value is
found?
Find index returns the position of an element in an object. If the requested element is not found
then -1 is returned.
var index = $scope.items.findIndex(record => record.date =='2018-12-12');
15. Can I set an angular variable from PHP session variable without sending an HTTP
request?
Yes, we can do that by injecting PHP in the required place.
This will work only if you are using PHP to render the HTML and the above javascript is writter
in <script> tag inside the php file.
16. What is the significance of pipe operator in angularJs and What would be the result of
following expression
{{ Somevalue|lowercase|uppercase}}
Pipe operator in AngularJS represents filters that are used on the expression. The preference
order is from left to right. So, the result of the above expression would be SOMEVALUE.
Here, setFinalFilter is a custom filter used on the hotels object. The result would display the
name of filtered hotels in ascending order of their minPrice.
app.service('sharedData', function () {
//methods to get and set variable
});
19. What is dependency injection and what are the benefits of it?
Dependency injection is a powerful design pattern that allows separating the concerns of
different components in an application and provides a way to inject the dependent component
into the client component.
.$http, $location are all services which are injected into the controller as a dependent entity. All
of them have some independent specific task associated with it. MyController does not need to
create their instance, but it can directly use them.
$scope.newDate=new Date();
21. Can parent controller access the methods of child controller or vice versa?
No, the parent controller cannot access the methods of child controller, but the child controller
can access the methods of the parent controller.
This code will give a syntax error. We cannot use ng-options without ng-model. Using the array
or object obtained by evaluating the ngOptions expression, the ngOptions attribute dynamically
generates a list of < option > elements for the < select > element. On selecting an item in the <
select > menu, the array element or object property will be bound to the model identified by the
ngModel directive. Hence, ng-model is must with ng-options.
When ng-repeats is used with the object having some unique id, the tracking should be done by
that identifier, instead of the object instance. Consider the below code.
.directive('testDirective', function() {
return {
scope: {},
link: function(myScopeVar, elem,attr) {
console.log(scope)
}
}
})
})
In the above code, a directive with an isolated scope is declared. The link used in above code is a
regular Javascript function with signature scope, element and attribute. The name of scope object
is not important because whatever name you give to this element, it will be linked to the
directive’s scope object. That is why, using myScopeVar will not give any error. The $scope, on
other hand, cannot be used with any other name.
For further clarification, let us see the following code:
app.controller(‘myController’,function(newScope)
{
})
The above code will give an error. Here are more details on scope v/s $scope.
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
templateUrl: 'my-customer.html'
};
});
Here, a custom directive of name myCustomer is declared. The directive is restricted to element
name only. The directive has its own isolated scope which has a property customerInfo and takes
its value from info attribute of the myCustomer element.
Link, on the other hand, combines the model with a view. Any change in model reflects the
change in view and any change in view reflects in the model.
Here is more detail on compile and link.
Logs are maintained with the help of $log service. The main purpose of this service is to help in
debugging and troubleshooting. This is done with the help of four methods.
1. log()-writes a log message in the console
2. info()-writes an information message
3. warn()-write a warning message
4. error()-writes an error message
5. debug()-writes a debug message
It is not a plugin or browser extension since it is based on JavaScript and compatible with both
desktop and mobile browsers.
There are some built-in filters provided by AngularJS like Currency, Date, Number, OrderBy,
Lowercase, Uppercase, etc.
2. Factory
3. Provider
4. Value
5. Constant
12. What are the exit codes in Node.js? List some exit codes?
Answer: Exit codes are specific codes that are used to end a “process” (a global object used to
represent a node process).
Examples of exit codes include:
Unused
Uncaught Fatal Exception
Fatal Error
Non-function Internal Exception Handler
Internal Exception handler Run-Time Failure
Internal JavaScript Evaluation Failure
13. Why is consistent style important and what tools can be used to assure it?
Answer: Consistent style helps team members modify projects easily without having to get used
to a new style every time. Tools that can help include Standard and ESLint.
14. What Are The Main Features Of AngularJS?
Answer: Here is the list of AngularJS features that makes it the hottest tech for web dev.
Data-binding – Handles synchronization of data across model, controllers, and view.
Scope – Object representing the model, acts as a glue layer between controller and view.
Controllers – JS functions bound to the scope object.
Services – Substitutable objects that are wired together using dependency injection. e.g.
$location service.
Filters – Formats the value of an expression for displaying to the user. e.g., uppercase, lowercase.
Directives – These are extended HTML attributes start with the “ng-” prefix. e.g., the ng-app
directive used to initialize the angular app.
Templates – HTML code including AngularJS specific elements and attributes.
Routing – It’s an approach to switch views.
MVC pattern – A design pattern made up of three parts.
Model – Represents data, could be static data from a JSON file or dynamic data from a database.
View – Renders data for the user.
Controller – Gives control over the model and view for collating information to the user.
Deep linking – Enables the encoding of the application state in the URL and vice versa.
Dependency injection – A design pattern to let the components injected into each other as
dependencies.
If there is any change in the value of the given variable or expression, then the content of the
specified HTML element will also be updated accordingly. It supports one-way binding only.
ng-model – This directive is used to bind the value of HTML controls (input, select, text area) to
application data. It is responsible for linking the view into the model. Directives such as ‘input’,
‘text area’, and ‘select’ require it. It supports two-way data binding.
ng-class – This directive dynamically binds one or more CSS classes to an HTML element. The
value of the ng-class directive can be a string, an object, or an array.
ng-app – Just like the “Main()” function of Java language, this directive marks the beginning of
the application to AngularJS’s HTML compiler ($compile). If we do not use this directive first,
an error gets generated.
ng-init – This is used to initialize the application data so that we can use it in the block where it
is declared. If an application requires local data like a single value or an array of values, this can
be achieved using the ng-init directive.
ng-repeat – This repeats a set of HTML statements for the defined number of times. The set of
HTML statements will be repeated once per item in a collection. This collection must be an array
or an object.
We can even create custom directives and use them in our AngularJS Application.
1) As an attribute:
2) As a class:
3) As an element:
4) As a comment:
Compile – It looks into the entire DOM and collects all of the directives. The result is a linking
function.
Link – It combines the directives with a scope and produces a live view. Any changes in the get
reflected in the view and any operations done by the user in the view gets reflected in the.
The concept of compile and link has come from the C language. Here the code is compiled first
and then linked.
23. How Is AngularJS Compilation Different From Other JavaScript Frameworks?
Answer: Javascript frameworks like backbone and jQuery process the template as a string and
returns the result as a string. You have to dump this resulting string into the DOM where you
wanted it with innerHTML().
AngularJS process the template in another way. It directly works on HTML DOM rather than
strings and manipulates it as required. It uses two-way data binding between the model and view
to sync the data.
3. In the traditional concept, HTML pages are decided by interacting with server-side program
and as we using single page application, pages are decided without any server-side interaction.
So required part of the page will be updated.
25. Which is the core module in AngularJS?
Answer: ng” is the core module in AngularJS and this module will be loaded by default when
the angular application has started.
26. Explain factory methods in AngularJS?
Answer: Factory methods are used for creating a directive. It can be invoked only once that is
when compiler matches the directive.
27. What Is $RouteProvider In AngularJS?
Answer: $routeProvider is the primary service which set the configuration of URLs, map them
to the corresponding HTML page or ng-template, and attach a controller with the same.
Let’s see the following example:
var mainApp = angular.module(“mainApp”, [‘ngRoute’]);
mainApp.config([‘$routeProvider’, function($routeProvider) {
$routeProvider.
when(‘/addEmployee’, {
templateUrl: ‘addEmployee.htm’, controller: ‘AddEmployeeController’
otherwise({
redirectTo: ‘/addEmployee’
routeProvider is defined as a function under the config of the mainApp module using a key as
‘$routeProvider.’
$routeProvider.when defines a URL “/addEmployee” which is then mapped to
“addEmployee.htm”. This should be present in the same path as the main HTML page.
“otherwise” is used to set the default view.
“controller” is used to set the corresponding controller for the view.
Back to top
28. What Is Data Binding? How Many Types Of Data Binding Directives Are Provided By
AngularJS?
Answer: Data binding is the connection bridge between view and business logic (view model) of
the application. Data binding in AngularJs is the automatic synchronization between the model
and view. When the model changes, the view is automatically updated and vice versa. AngularJs
support one-way binding as well as two-way binding.
29. What are typings in Angular?
Answer: Typings is a way of installing the Typescript definitions using typings.json file, as it is
necessary as the browser does not understand typescript natively and hence it must be transpiled
first before rendering.
30. What are module loaders in Angular?
Answer: Module loaders in Angular are used to bundle different modules that contain
their dependencies along with angular components into one bundle or multiple bundles (For lazy
loading) and load them in the browser.
31. What is the use of systems? How is webpack better to use in Angular?
Answer: System is a client-side module bundler in angular as it loads modules (components and
other files) on demand instead of loading an entire application at startup.
This largely reduces load times while starting up the app.
The upside of Webpack over Systems is that it bundles and creates a single file called bundle.js,
which contains HTML, CSS, and JS, etc.
While the initial load time might take a few seconds once the app is cached it becomes lightning-
fast and will lead to a large boost in performance.
32. What Is An Auto Bootstrap Process In AngularJS?
Answer: AngularJS initializes automatically upon the “DOMContentLoaded” event or when the
browser downloads the angular.js script and at the same time document.readyState is set to
‘complete.’ At this point, AngularJS looks for the ng-app directive which is the root of the
Angular app compilation process.
If the ng-app directive is located, then AngularJS will do the following.
34. Mention what are the styling form that model adds to CSS classes?
Answer:
the model adds these CSS classes to allow styling of form as well as control:
1. ng- valid
2. ng-invalid
3. ng-pristine
4. ng-dirty
By doing so, Angular will skip SQLite and will start to use the jQuery library.
38. What Is The Difference Between The $Watch, $Digest, And $ Apply?
Answer: In AngularJS $scope object is having different functions like $watch(), $digest() and
$apply() and we will call these functions as central functions. The AngularJS central functions
$watch(), $digest(), and $apply() are used to bind data to variables in view and observe changes
happening in variables.
A) $Watch() –
The use of this function is to observe changes in a variable on the $scope. It triggers a function
call when the value of that variable changes. It accepts three parameters: expression, listener, and
equality object. Here, listener and equality objects are optional parameters.
1. What is AngularJs?
Ans: AngularJs is an open-source JavaScript framework that helps to build high scale and
extensible web applications. It works with HTML and JavaScript. All the components can be
mentioned clearly in the applications using HTML. It is best for single web page applications. It
is used in the combination of HTML UI elements with JavaScript objects.
2. What is the Angular framework?
Ans: Angular is a typescript and an open-source web application that is maintained by Google
and a community of individuals. It provides a platform to develop web-based applications.
Angular integrates a range of features like dependency injection, declarative templates, end to
end tooling, and various other features that helps to smoothen the development path.
3. List out the difference between Angular and AngularJS?
Ans:
AngularJS Angular
It uses JavaScript to build the application. It uses TypeScript to build the application.
It is difficult to create SEO friendly application It is easy to create SEO friendly application
development. development.
In AngularJS, code can be written by using ES5, In Angular, code can be written by using ES5,
ES6, and Dart. ES6, TypeScript.
AngularJS works on client-side like Angular 2 works on the server-side and client-
html/javascript. side.
It initializes the application by using ng-app and Angular initializes the application by using a
bootstrap functions. boostrapmodule() function.
Specific ng required for an event and the Uses [] for property binding and () to bind an
image/property event.
It doesn’t support the dependency injection It supports the hierarchy dependency injection
concept.
For routing config $routeprovider.when() is used For routing config @RouteConfig{(…)} is used
document.body.innerHTML = greeter(user);
11. What are the building blocks of Angular?
Ans: The main building blocks of Angular are modules, components, templates, metadata, data
binding, directives, services, and dependency injection.
12. What are the advantages of Angular?
Ans: The following are the advantages of Angular:
• It supports data-binding capability to HTML. It provides a rich and responsive experience
to the users.
• It provides the capability to create single-page applications effectively.
• Supports angular and static templates
• It allows both server and client-side communication
• It has custom directives
• Support dependency injection
• AngularJs code is unit-testable
• It has a wide range of features like Animations, Event handlers, Annotations, etc.
13. Where can we implement DOM in AngularJS?
Ans: AngularJs DOM manipulation is performed in controllers, directives, and services.
14. Define the ng-content Directive?
Ans: Html tags have some content between the tags, for example
1 <p> Hai! Welcome! </p>
Now, consider the following instance of having the custom text between the angular tags
this tag doesn’t work like HTML tag until you use ng-content directive
15. What are Angular expressions?
Ans: Angular expressions are used to bind the application data to HTML. It displays the data
exactly at the place where the expression is placed. The expression can be written inside double
braces: {{expression}}
16. Explain the various features of Angular?
Ans: Data Binding: It synchronizes the data between the model and view components.
• Controllers: It is a javascript function which specifies the scope and the primary
component of Javascript. It helps to carry out functions to operate views and data.
• Scope: These are the objects that are referred to as the model. They act as a glue between
view and controller.
• Services: AngularJs has several built-in services like $http to make XMLHttpRequests.
These services are singleton objects
• Filters: Filters select a subset of items from an array and return a new array.
• Directives: Directives are markers on DOM elements such as attributes, CSS, elements,
and more. Using these elements, users can create custom html tags that serve as new custom
widgets. AngularJs comes with several built-in directives such as ngModel, ngBind, etc.
• Templates: It views the information from the controller and model. This can be single or
multiple views on one page using partials.
• Routing: It switches the views.
• MVC: It is a design pattern for dividing an application into different parts called model,
view, and controller; each part has its distinct responsibilities.
17. Discuss the disadvantages of using Angular?
Ans: Due to Javascript Angular has few limitations. The following are the limitations:
• Less Secure: Angular is a Javascript framework, it does not provide proper
authentication and authorization to the users.
• Javascript Dependent: AngularJs does not work if the end-user disables the javascript.
• No specific path: AngularJs have multiple ways to do the same task. Hence, it is difficult
for programmers to predict which is the best way to perform certain tasks.
• Lagging UI: More watches can degrade the performance of the application.
• Name Clashes: If you create more ng-apps on a single page, it may lead to cause name
clashes.
AngularJs does not support Internet Explorer 8.0.
18. What is a SPA (Single Page Application) in Angular?
Ans: A single page application is a web site or a web application that interacts with the users
dynamically. It rewrites the current page instead of loading the entire page from the server.
19. Explain Angular Authentication and Authorization?
Ans:
Authentication: Authenticate API verifies, user login credentials that are present in the server.
After completion of the validation, it returns JWT (JSON Web Token) to the users. The JWT
token has current user information and it identifies the users. This is called authentication.
Authorization: Every user has a different level of resources access. While some users have
access to all the resources, others may have access to the few files or resources. This is called
authorization.
In order to build authentication, on the client we need to build the login page and on the server,
we should build an API endpoint to validate the user. When the user clicks on the login button.
20. Explain what is the difference between Angular and backbone.js?
Ans:
Feature AngularJs Backbone.Js
Definition AngularJs is an open-source framework based on front-end web application
BackboneJs is a lightweight javascript with RestFul JSON interface, and it offers a
framework based on MVC
Performance It provides intense performance for big/large pages as it processes the two-way
data binding. It also provides impactful performance than AngularJs for small pages, but for
large pages, it is not preferred as it does not offer any data binding.
Architecture It works on MVC It works on MVP
architecture, and it uses two-way data binding to lead the application activity.
architecture, and it does not provide any data binding process to drive the application
activity.
Templating To understand the application at the function level, AngularJs offers templating
through the dynamic HTML attributes which are added to the document. BackboneJs provides
an underscore template which is not fully featured as angularJs templates.
Testing It prefers unit testing for large applications. It prefers swift testing for small or
single-page applications.
Support AnuglarJs has extensive documentation libraries and large community support.
BackboneJs also have great community support.
AngularJs is a bit complex than BackboneJs because it implements two-way data
binding. BackboneJs is simple because it does not provide data binding.
Angular Intermediate Interview Question and Answers:
21. How do Observables differ from Promises?
Ans:
• Observable is lazy, where the promise is easy
• Observable can be either synchronous or asynchronous, where the promise is always
asynchronous.
• Observable can handle a stream of values (from zero to multiple values), where the
promise can handle a single event.
• A call back is made for each event in the observable.
22. What are the Routes in AngularJS?
Ans: Routes in AngularJS helps to create different URLs for different contents in the
applications. This enables the user to bookmark a specified content which is needed. This
bookmarked URL is called Route.
23. Define value in Angular?
Ans: Value refers to a simple object, it may be a number, character, and string. The value should
always belong to a model and these are injected into controllers, factories and services. Adding
value to the controller is possible by assigning parameters with the same name as the value.
24. What are the linking functions and types of linking functions?
Ans: A linking function links the directives with the scope to produce a view. To register and to
update DOM handlers, the linking functions are very important. There are two types of linking
functions, they are:
Pre-linking functions: This function is executed before the process of child elements linking.
Here we can’t transform the DOM.
Post-linking functions: This function is executed after the linking process of child elements. In
these functions, the transformation of DOM is done safely.
25. What are templates in Angular?
Ans: Templates in AngularJs are an HTML file that is enriched or filled with the AngularJs stuff
like directives and attributes. A directive is an essential element that is used to specify a
particular class or attribute to know its behaviour according to the user needs. The controller and
model in angular are combined with the templates to handle the user views. Angular templates
can also include Form controls, Expressions, CSS and Filters.
----- Related Page: Full Stack Developer Interview Questions -----
26. What is string interpolation in Angular?
Ans: In angular, string interpolation is a syntax that uses to display the component data on the
HTML template at the end-user. It facilitates you to fetch the data from the html template file
and also to make changes on component.ts file. It is represented with the double curly braces
({{ }} ).
27. What is the difference between an Annotation and a Decorator in Angular?
Ans: In angular, annotations are the only metadata set of classes using the reflect metadata
library and use to create the annotation array. On the other hand, decorators are also called
design patterns and it is used for separating modifications or decorations of the classes without
changing the original source code.
28. What is a provider in Angular?
Ans: Provider is a unique and critical feature of Angular. It is an instruction to the dependency
injection system and provides the data to obtain values for the dependency. A provider is an
object that has a $get method to create a new instance service. To register new providers it uses
$provide method and other additionals methods.
29. Does Angular support nested controllers?
Ans: Yes, angular support nested controllers concept. Nested controllers are needed to
demonstrate the hierarchy manner for using it in the view.
30. Explain the differences between Angular and jQuery?
Ans:
Angular JQuery
AngularJs is tough to understand Jquery is easy to understand.
AngularJs support two-way binding Jquery does not support any data binding process
Angular support deep linking routing Jquery does not support deep linking routing
In angular components are the building blocks for UI in the application Jquery components
are Jquery UI which are set of effects, user interface, themes, and widgets on
the top of the Jquery javascript libraries.
31. What is dependency injection in AngularJS?
Ans: In AngularJS, the dependency injection is a software mechanism in which the components
are given their dependencies instead of hard codes. It helps in maintaining a component as
reusable and extensible. It provides key components like value, service, constant, provider and
factory in which the dependencies are injected from one to the other.
32. What is Angular Material?
Ans: Angular Material is a UI component library that helps to build an attractive functional web
application, consistent, and web pages while sticking to the web design principles like device
independence, graceful degradation, and browser portability. It helps in creating wonderful,
responsive, and attractive websites.
33. What is the AOT (Ahead-Of-Time) Compilation?
Ans: Angular ahead of time AOT compiler converts your typescript code and angular html into
the javascript code during the build phase before the browser download and run the code. Before
developing the process, compile your application; it provides a faster rendering in the browser.
34. What is Data Binding? How many ways it can be done?
Ans: Data binding is a powerful and essential feature in any software development language. It
allows us to demonstrate communication between view and component. The following are the
different types of data binding:
• Event binding: It is defined as sending/updating the information of certain variables from
view to the component.
• Property binding: It is defined as updating the information/values of a certain variable
from component to view.
• Two-way binding: It is a combination of event and property binding. It defined as
updating the values or information from components to view and from view to the component.
35. Differentiate between one-way binding and two-way data binding?
One-way data-binding:
• In one-way data-binding, the UI or view part does not update systematically whenever
the data model changes. To update the changes, you need to write the custom code.
• The data flow only from objects to UI, not vice-versa.
Two-way data-binding:
• In two-way binding, the UI or view part is updated automatically whenever the data
model changes. Unlike one-way binding, two-way data-binding is a synchronization process.
• The data flows between the object to UI and vice-versa.
36. Explain the digest cycle in Angular?
Ans: The digest cycle in angular triggers the values when the model or view changed and the
cycle sets off the watchers to match the new values. The digest cycle automatically runs the code
when the code encounters the directives. The scope of the digest cycle is limited to the AngularJs
context. $apply() or $digest() is required to synchronize the changes in model and view that
happen outside the angular framework.
37. Could you explain the various types of filters in Angular?
Ans: Angular filters allows us to format the data in order to display the data on UI without
changing the original format of the data. It is possible to add these filters to directives, templates,
controllers, and services. Filters can be used with the directives or expressions using pipe
symbol(|)
Syntax: {{expression | filterName:parameter }}
Various types of filter are enumerated as follows
Number Formats a numeric data as text with comma and fraction.
Currency Formats numeric data into specified currency format and fraction.
Date Formats date to a string in the specified format.
Uppercase Converts string to uppercase.
Lowercase Converts string to lowercase.
Filter Filters an array based on specified criteria and returns a new array.
orderBy Sorts an array based on specified predicate expression.
Json Converts JavaScript object into a JSON string
limitTo Returns new array containing specified number of elements from an existing
array.
38. What is ngOnInit ()? How to define it?
Ans: ngOnInit () is a lifecycle hook that is called after completion of initializing all data-bound
properties of a directive. It is defined as:
Interface OnInit
{
ngOnInit () : void
}
39. What is the code for creating a decorator?
Ans:
1
2
3 unction Dummy(target) {
dummy.log('This decorator is Dummy', target);
}
Angular Advanced Interview Questions:
40. What is the process to convert TypeScript code into JavaScript code?
Ans: The Typescript code is not understandable by the browsers. So, the typescript code is
compiled and translated into the javascript code; this process is called trans-piled.
41. What is ViewEncapsulation and how many ways are there to do it in Angular?
Subscribe to our youtube channel to get new updates..!
Ans: ViewEncapsulation identifies the component styles and demonstrate that whether the
particular component will affect the entire application or not. It also enables us to use the DOM
shadow. Angular provides 3 types of ViewEncapsulation.
ViewEncapsulation.none: It defines the component style that is visible to all components of the
application.
ViewEncapsulation.emulated: Styles are used in other HTML, spread the components.
ViewEncapsulation.native: Styles are used in other HTML but does not spread the components.
42. Why prioritize TypeScript over JavaScript in Angular?
Ans: Typescript gains much popularity in recent years. It is a superset of Javascript. The issue
with the javascript is, it does not support OOP language and does not follow proper prototype
patterns. In Javascript, it is a tough task to handle the errors in the code, but in typescript, it is
easy for the team to handle the errors.
43. What is a template?
Ans: view that a user sees in the browser.
44. How to perform animation in Angular?
Ans: To implement the animation in an angular application, a user needs to include an angular
library known as Animate Library. Then you must refer ngAnimate module into your application
or add if your application has name, add ngAnimate as a dependency inside your application
module.
Angular library:
1
2 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-
animate.js"></script>
<body ng-app=”ngAnimate”>
45. What is transclusion in Angular?
Ans: The transclusion in Angular allows you to shift the original children of a directive into a
specific location within a new template. The ng directive indicates the insertion point for a
transcluded DOM of the nearest parent directive that is using transclusion. Attribute directives
like ng-transclude or ng-transclude-slot are mainly used for transclusion.
46. What is a module?
Ans: In angular, a module is a process to group directives, pipes, services, and components that
are related, in such a way that they can blend with other modules to create an application.
Instance:
app.module.ts root module declared with @NgModule decorator as below,
1
2
3
4
5
6
7
8
9
10 import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule ({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
47. What lifecycle hooks are available in Angular?
Ans: Angular has a lifecycle from initialization to the end of the application. The following are
the lifecycle hooks of angular.
Hook Purpose and Timing
ngOnChanges() This method accepts a SimpleChanges() object of previous and current
property values and retorts when Angular resets the data-bound input properties — called before
ngOnInit() more than one data-bound input properties change.
ngOnInit() This method initializes the components after angular displays the data-bound
properties and sets the components input properties. Called ngOnchanges() method.
ngDoCheck() This method identifies and acts upon the changes that Angular can’t detect on its
own. This method called during the changes and after ngOnchanges() and ngOnInit() methods.
ngAfterContentInit() This method addressed the Angular external content projects and called
after the ngDoCheck() method.
ngAfterContentChecked() This method responds after the Angular checks the projected
content into the components. And it is also called after the ngAfterContentInit() method and
every subsequent ngDoCheck() methods.
ngAfterViewInit() This method responds after Angular initialized the child's views that are in
directives. It is called after ngAfterContentChecked() method.
ngAfterViewChecked() This method also checks the component’s view that is in the
directives. It is called after ngAfterContentChecked() method.
ngOnDestroy() This method cleans the data before Angular
wrecks the components. To avoid the memory leaks, unsubscribe the detach event
handlers and observables- Called just before Angular destroys the directive/component.
48. What is metadata?
Ans: Angular metadata is used to decorate a class that demonstrates the expected behavior of the
class. The following are various parts of the metadata.
1. class decorator: @NgModule and @Component
Instance:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import { NgModule, Component } from '@angular/core';
@Component({
selector: 'my-component',
template: '<div>Class decorator</div>',
})
export class MyComponent {
constructor() {
console.log('Hey I am a component!');
}
}
@NgModule({
imports: [],
declarations: [],
})
export class MyModule {
constructor() {
console.log('Hey I am a module!');
}
}
?
2. Method decorators: It is used for methods inside the classes. Eg: @HostListner.
Instance:
1
2
3
4
5
6
7
8
9
10
11
12 import { Component, HostListener } from '@angular/core';
@Component({
selector: 'my-component',
template: '<div>Method decorator</div>'
})
export class MyComponent {
@HostListener('click', ['$event'])
onHostClick(event: Event) {
// clicked, `event` available
}
}
3. Parameter decorators: It is used for parameters inside the class constructors, eg- @Inject.
Instance:
1
2
3
4
5
6
7
8
9
10
11
12 import { Component, Inject } from '@angular/core';
import { MyService } from './my-service';
@Component({
selector: 'my-component',
template: '<div>Parameter decorator</div>'
})
export class MyComponent {
constructor(@Inject(MyService) myService) {
console.log(myService); // MyService
}
}
4. Property decorators: It is used for properties inside the classes, eg- @Inside, @Outside.
Instance:
1
2
3
4
5
6
7
8
9
10
11 import { Component, Input } from '@angular/core';
@Component({
selector: 'my-component',
template: '<div>Property decorator</div>'
})
cookie.set('nameOfCookie',"cookieValue");
To get Cookies: For retrieving the cookies ‘get’ method is used.
cookie.get(‘nameOfCookie’);
To clear Cookies: For removing cookies ‘remove’ method is used.
cookie.delete(‘nameOfCookie’);
57. What is the difference between pure and impure pipes in angular?
Ans: Pure pipe detects the change in the value or parameters that passed through a pipe symbol.
For example, any changes made in the input values like strings, integers, booleans or in the
object reference like array, function, objects.
Impure pipe detects every change in the expression whether it is parameter or value, it also
detects the changes in the keystroke and mouse-move.
58. What are the differences between the factory service methods in AngularJs?
Ans: In a factory method, first a factory of objects is defined and then methods are implied to
those factories, whereas in the service method, the services are created to define a specific task.
59. Explain about Routing?
Ans: Routing is a process of merging views. The controller decides which view should be
merged based on the logical need.
60. Explain the AngularJs boot process?
Ans: When a page has loaded in the browser, the following process takes place:
• An HTML document of the page is loaded and evaluated by the web browser. A
Javascript file is loaded and the global object is created. Later controller functions are executed,
which are registered by Javascript.
• Here Javascript scans views and apps through HTML, once the view is scanned, then it is
connected with the controller function.
• Then AngularJs shows the controller functions with views and data handled by the
controller. Finally, the page gets ready.
Angular 2 Interview Questions
1. What is Angular2?
Ans: Angular2 is an entirely revived component based javascript framework in which an
application is coupled with the components. Angular2 is an advanced version of AngularJs and it
is more “all in one” framework so it also helps in creating the websites without struggling with
the different AngularJs frameworks.
Angular2 is a modular framework in which our code is partitioned into specific procedures that
provide similar functionalities, hence it improves the up-gradation, testing, and maintaining the
application. It has plenty of useful features including cross-platform, server-side rendering, and
supports many languages than other frameworks.
2. What are the new features in Angular 2?
Ans: Angular2 is a platform that encloses a wide range of competencies. The following are the
some of the features that are added to the Angular2.
• Modular: To get the better performance, various modules are removed from angular’s
core.
• Data-binding: In angular2 data binding has been improved. To bind the DOM element
property, you just wrap into the square brackets. Eg:
• Modern: Angular2 is targeted to the modern browsers in which various hacks that make
angular harder to develop have been removed.
• Mobile toolkit: To develop high performance in mobile applications, Angular2 provides
mobile toolkit and techniques. The web applications which are built using mobile toolkit can be
loaded on any device without or with internet connection, which is a great advantage.
• A command line interface: With the help of commands it can generate route, pipes,
components, and services.
• Universal server rendering: It is the prominent feature of Angular2. It is a library which is
used to develop the universal applications as a smoothen experience.
3. What are the key components in Angular 2?
Ans: Angular2 components are:
• Modules: An application is broken down into several pieces of code. Each piece is called
a module. These modules are created to perform certain specific jobs.
• Components: Components are used to build a module.
• Meta Data: It is used to add extra data to the JavaScript class.
• Templates: It is used to specify the views of applications in JavaScript.
• Service: These are used to create components.
4. How to declare the components in Angular 2?
Ans: In Angular2 components are directives that are allied with a template. Components have an
well-defined lifecycle, so you can utilize interfaces that allows you to implement functionality
for different times in a component's lifecycle. A component must be NgModule in order to
usable by an application or another component. Components can control their run time behavior
by using lifecycle hooks.
Declaration of component:
1
2
3
4
5
6
7 @component ({selector: 'great', template: 'hello {{name}}!'})
Class greet{
}
5. What are the directives in Angular2?
Ans: A directive is an element that is used to customize HTML code. The important directives in
Angular 2 are:
ngIF- If it is true then the elements are added to the HTML code, either elements are not added
to the code.
ngFOR- It is used to get a temporary variable from the variable list.
6. How to handle errors in Angular 2?
Ans: Errors handling feature is available in Angular2 applications. The errors that occurred in the
application can be handled by the React JS catch library and also by using the catch function.
7. How Angular 2 is better from Angular 1?
Ans: Angular2 is a rewrite version of Angular1. It is not an updated version of angular1. Angular
2 is an extensible version when compared to the Angular1. We have listed some features which
are different in Angular2 from Angular 1.
Angular 2 Angular 1
It is a mobile development framework It is not suited for mobile development
In Angular2 there are more language options and we can write code in ES6, ES5, Dart and
Typewriter. In Angular1 we can write by using ES6, ES5, and Dart.
Angular2 is an extensible framework and it is completely component-based. It is a
controller-based framework.
8. List the difference between Angular 2 components and directives.
Ans: There are certain differences between the components and directives in angular2. They are:
Component Directive
A component is a directive with a view. A directive is a decorator without a view.
Components are the specific type of directive that allows you to utilize the web component
functionality throughout the application. Directive is the mechanism by which we attach
behavior to the elements.
It divides the application into smaller components. It is used to design the reusable components.
Components define pipes Directives cannot define pipes.
Component can be present per DOM element. Directive is used to add behavior to the
existing DOM element.
9. What is ECMAScript?
Ans: ECMAScript stands for European Computer Manufacturer’s Association and it is a
standard for scripting languages. It is a subset of Javascript. Javascript and Actionscript use
ECMAScript as its core language. Developers commonly use ECMAScript for client-side
scripting on the world wide web and also it is used for server services and applications.
ECMAScript includes dynamic, functional, prototype, and structured features.
10. What is a Traceur Compiler?
Ans: Traceur compiler takes generators, classes and other features from ECMAScript and
compiles it into the JavaScript ES5 that runs on the browser. This means developers can utilize
the code from updated version which has more number of features and design patterns.
11. How to convert a string into currency?
Ans: To convert a string input into a currency type we use currency filter in Angular 2.
Here is an example of adding a currency filter by using pipe character to the expression
The currency of this expression is{{ new value/ currency}}
12. Explain about hidden property in Angular 2?
Ans: Hidden property is one of the special case properties in angular 2. It is used to bind
elements from one property to another property. It can set the display property to none.
13. Is there any chance to port Angular 1 code to Angular 2?
Ans: There is no such chance of porting the code from Angular1 to Angular2. Till there is no to
port code. As they are different frameworks, they require some approaches.
14. When to use Ngoninit and constructor in Angular 2?
Ans: Constructors are used for dependency injection and for initializing class members. Ngonlnit
is used for initialization work. Constructor and Ngonlnit methods are called when the component
is created. It is essential to know when to use the methods. These methods are used to provide
best structures for your component’s code.
A constructor method is a predefined method in the constructor class which is called when the
class is instantiated and also used for initializing the fields. In Angular2 constructors are used to
create an instance of the class. When we implement the constructor to use in the class then
import the Ngonlnit class.
15. How to cache an observable data in Angular 2?
Ans: Caching of an observable data is done with the help of “observable.cache”. We can use
caching in order to cache the response in the memory and then, on the next subscription, instead
of requesting the remote server again. This operator is used at the end of the string.
Caching is important for the performance, especially on bandwidth restricted devices and slow
networks. You should have a good understanding of caching while working with promises but
while translating it to observable, it is a bit difficult. Therefore, when interacting with
observables, we typically set up a subscription on the consumer side and react to values coming
through the pipe. We can easily add caching to the observables by adding publishReplay(1) and
refCount.
Angular 4 Interview Questions
1.Explain component decorators in Angular4?
Ans: A decorator is an essential concept when developing an angular framework with the
angular4. In Angular4 decorators are used to compile the code and also used comprehensively.
There are four different types of decorators.
• Class decorator
• Property decorator
• Method decorator
• Parameter decorator
A decorator is a function that is invoked with a prefixed “@” symbol and is immediately
followed by property, parameter, methods and class. A decorator return the same thing which
was given as input but in an augmented form.
2. What is the isolated unit test in Angular 4?
Ans: The process of conducting tests on the class or component of the angular in an isolated way,
rather than creating dependency in between the components is called isolated unit test. In
isolated testing, every component and unit is tested under isolation.
3. Explain about pure function in Angular4?
Ans: Pure functions do not change the assigned value and produce the exact output, after
assigning the same value for multiple times.
4. Write the CLI command to generate a component in Angular4?
Ans: Components are simple classes that are declared as components with the help of component
decorators. It becomes easy to create an application that 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;
It generates the component and adds the component to module declarations.
5. Explain the component directory structure of Angular4?
Ans: The following are the component directory structure of Angular4:
Module.ts: Angular module is declared and @NgModule decorator is used which initializes the
different aspects of angular applications.
components.ts: It defines app-root sector and components in angular. A tiny attribute is also
declared in the component.
component.html: it is the template file of the application which represents the visual part of our
components.
6. Explain ngFor directive with an example?
Ans: The ngFor directive instantiates a template for every element of the given iterator. The
different local variables of the ngFor directive can be used in iterations. The ngFor directive can
even be used with the HTML elements. It also performs various changes in DOM. Several
exported values can be aliased to local variables with the help of ngFor directive. It allows us to
build data presentation lists and tables in our HTML templates. Here’s an example of ngFor
directive with the help of HTML:
({hero.name})
7. What do you understand by isolated unit tests?
Ans: Unit testing is all about to test the individual units of code.
As the name implies, the unit test is all about testing individual units of code. In order to answer
some questions, isolating the unit of code under test is really important. When we do this, we are
not forced into creating related pieces such as DOM elements for sorting. With the help of
isolated unit tests, it becomes easier to implement everything. To simulate the requests,
dependency injections are also provided. The individual sort function can be tested in isolation.
And not only the sort function, any function can be tested in isolation.
8. What are the DSL animation functions in AngularJs. List them?
Ans: DSL Animation functions are used for crafting animations in Angular js. Below are list of
DSL Animation functions in angular js.
• group()
• state()
• transition()
• style()
• keyframes()
• trigger()
• sequence()
• animate()
9. How to include an external css in angular4?
Ans: To include external CSS in Angular 4, open your .angular-cli.json and add your css file
path in styles array.
10. How angular4 is different from angular2?
Ans:
• Angular 4 is much faster and smaller than Angular 2.
• The size of the View Engine is reduced in Angular 4.
• New ngTemplate directive is introduced.
• Coding Improvements in *ngIf and *ngFor directives are performed.
• NgIf directive with Else is introduced for better UI handling.
• New Pipes like titlecase is introduced.
• Meta Tags services are added.
• Improvement in Angular Router.
Angular5 Interview Questions
1. What are the new features in Angular5?
Ans: Angular5 came with a lot of new features that help and attract the developers at any point of
time on Angular task. The following are the Angular5 new features.
• AOT is a default feature.
• Type checking utility for the template.
• Activated watching mode that helps developers to debug the errors.
• Saving metadata and fetching utilities.
• Unwanted files are removed permanently( *.ngfactory.ts)
• Displaying error message to help developers to handle the error investigation.
• Feature upgrades are smooth then earlier.
• Introduced tree shakeable components.
• Hybrid upgrade applications.
• Improve performance more than the earlier versions.
2. Provide proper generation logic of Component, Pipe, Class, Directive, Service, and Module
for Angular 5?
Ans: In Angular5 commands are little different than before Angular versions:
Component: – ng g component my-new-component
Pipe: ng g pipe my-new-pipe
Class: ng g class my-new-class
Directive: ng g directive my-new-directive
Service: ng g service my-new-service
Module: ng g module my-new-module
3. List the types of data binding supported by Angular5?
Ans: Angular5 supports four types of data binding. They are as follows:
• String Binding
• Property Binding
• Event Binding
• Two-way Binding
4. How to run an Angular 5 application locally during development?
Ans: To run angular 5 applications locally during the development ngserver command is used.
ngserver -p aPortNumber is used to start the development on a specific port.
5. What an Angular 5 component made of and how do you generate new components in Angular
5?
Ans: Angular 5 component is made of component definition and component decorator of a class.
To generate a new component in angular 5, use ng generates component component_name
command.
6. How do we import a module in Angular 5?
Ans: Below syntax is used to import a module in Angular5.
import { ModuleName } from 'someWhere';
7. Explain $event in Angular 5?
Ans: $event is a reserved keyword that provides the data emitted by an event. It is used as a
parameter for event based methods.
8. Why double curly brackets are used in Angular 5?
Ans: In Angular 5, double curly brackets are used for data interpolation.
9. Explain the logic of Event Emitters and how Angular 5 makes it work?
Ans: Event Emitter is one of the classes using to emit custom events.
@output() something changed = new EventEmitter();
10. Explain with example @Input and @Output in Angular 5?
Ans: @Input(alias): here alias is the component name that needs binding.
Same like @Output (alias).
Angular 6 Interview Questions
1. What is new in Angular 6?
Ans:
• Added support for creating Custom Elements based on Angular Components.
• Animations: expose elements and params within transition matchers.
• Bazel: change ng_package rule to APF v6
• Single line, multiline and jsdoc comments are now supported
• compiler-cli: add resource inlining to ngc
• support for TypeScript 2.7
• Require node 8 as runtime engine
2. Provide a clear difference with some proper examples of code snippet between “declarations”,
“providers”, and “imports” in ng module for angular 6?
Ans:
Declarations: This is one of the key features of Angular for available varieties components or
pipes of a single directive for the current module to other directives of the current module. If
someone is willing to use some of the same declare component in the current module from other
directives then declaration should need to be done properly.
Imports: Helping of availability of other module components in a current module by importing
the same.
Providers: It is helping DI for understanding and identifying using values and services.
3. How to generate a module in Angular 6?
Ans: In order to generate a module in Angular, cd to the current project directory and enter the
below command.
ng g module module_name
4. What is mean by ngzone?
Ans: The ngzone is a wrapper for the JavaScript files and denoted by Zone.js. These are the key
libraries in which the tracking of asynchronous functions. It helps in creating the context for the
functions.
5. Explain in detail with a proper example of genuine differences identified specifically between
“constructor” and “ngoninit” for Angular 6 version?
Ans:
Constructor: Constructor is one of the default declarations for any specific class or object, it can
be called every time when any class instantiated, also ensuring initialization properly of their
subclasses and different instance variable fields.
Ngonint: It is one of the first initialize method using by Angular, mention in the first component
of an angular life cycle. It mainly indicated that angular has been completed of creating entire
require components properly. It is not mandatory to use but the best practice to use.
6. What do you mean by the Bazel compiler in Angular 6?
Ans: Bazel compiler supports Angular 6 version and when you compile your entire code with
the Bazel compiler, it compiles with the necessary code only. The Bazel compiler uses advanced
and local distributing cache systems, parallel execution and optimized dependency analysis.
Angular 7 Interview Questions
1. Enumerate some salient features of Angular 7.
Ans: Following are the features of Angular 7:
• Angular Material gets Minor updates
• Better Accessibility for Selects
• Virtual Scrolling
• Drag & Drop
• Automated render as a user moves items
• Enhancing application performance.
2. How to generate a class in Angular 7 using CLI?
Ans: Create a class in Angular 7 using below code:
ng generate class [options]
ng g class [options]
Where name refers to the name of a class.
Options refer to the project name, spec value in Boolean or type of a file
3. What are the core dependencies of Angular 7?
Ans: There are two types of core dependencies in Angular 7: RxJS and TypeScript.
RxJS 6.3
RxJS version 6.3 is used by Angular 7. It has no changes in the version from Angular 6
TypeScript 3.1
TypeScript version 3.1 is used by Angular 7. It is the upgrade from the version2.9 of Angular 6.
4. How can you handle events in Angular 7?
Ans: There are various methods to handle events in Angular 7. The following are a few methods.
1. Binding to user input events.
2. Get user input from the event object.
3. Key event filtering.
5. Enlist types of forms in Angular 7?
Ans: The following are two types of forms in Angular 7:
Template-driven forms: All validations, controls, and logics are written in the template part.
Reactive Forms: It uses an immutable and implicit approach to handle the state of form at a
given point.
Angular 8 Interview Questions
1. What is Angular 8?
Ans: Angular 8 version is released in May 2019 and it is a javascript framework to build
applications in Typescript, HTML and Javascript. Angular 8 supports unique and new features
including angular material, CLI, and core framework.
2. What is new in Angular 8?
Ans: The following features are new in Angular 8.
• Typescript: Angular 8 supports typescript 3.4.
• Ivy: Angular 8 supports.
• Bazel: Angular 8 support Bazel compiler.
• Location: To help people migrating from AngularJs, a bunch of things added to the
location services in Angular.
• Differential loading: It is a technique to increase your application performance. When
you create applications for production, two bundles are created one bundle for older browsers
that support only ESS and another bundle for new browsers that support only ES6+.
Dynamic imports for lazy routes: Angular 8 uses standard dynamic import syntax so the syntax
is customized to Angular.
3. What is the difference between Angular 7 and Angular 8?
Ans:
Angular 7 Angular 8
It is difficult to use It is easy to use
It has features like CLI prompts, drag and drop, virtual scrolling, bundle budget, application
performance, Nativescript, Angular elements, better error handling, etc. It has new and unique
features such as differential loading, Ivy rendering, Bazel, location services, etc.
Breaking changing in Angular 7 are Virtual scrolling, material design library, and Component
Dev kit. Breaking changing in Angular 8 are CLI, Angular material and core framework.
It supports lower version of Typescript 3.4 It does not support a lower version of Typescript 3.4
It supports all versions of Node.js It supports Node.js 12 version.
4. What is bazel in Angular 8?
Ans: Bazel is a new feature in Angular 8 and it builds a new system that available for a short
period of time. It provides a platform to make your frontend and backend with a similar tool.
5. How performance improvements on the core in Angular 8?
Ans: Angular 8 has advanced and unique features that make sure systematic workflow and
performance improvements. It has apparent features like CLI workflow implementation,
differential loading, Bazel, Ivy rendering, and dynamic imports for lazy routes.
6. How to install Angular 8?
Ans:
Step 1:
Before installing Angular IDE using the Angular CLI tool, make sure that Node.js has already
installed it in your system.
• If Node.js is not installed in your system install it using the following steps.
• The basic requirement of Angular 8 is Node.js version 110.9.0 or later.
• Download node.js
• Install it on your system
• Open node.js command prompt
• Check the version run command, node-v in the console window
Step 2:
In order to install Angular CLI, use the following commands
npm install –g @angular/cli or npm install –g @angular/cli@latest
Step 3:
To check the node and angular CLI version, run command ng –version on the console terminal.
7. How to upgrade Angular 7 to 8?
Ans: Install TypeScript 3.4
• Use Node LTS 10.16 or its advanced version
• Run command on terminal panel/CLI -> ng update
8. What are the features of Bazel?
Ans: The following are the main features of Bazel:
• It is an internal build tool, through which application can be customized.
• It also tests the action and performance of multiple machines.
• It constructs a graph through which you can identify the useful information.
• It also supports customization.runGuardsAndResolvers
9. What is typescript in Angular 8?
Ans: The working of typescript in Angular 8 is similar with the enabled and disabled flag, which
means if you want to test whether the selected value is an object or not, then the following syntax
is used " Typeof value = = = 'object' ". In angular 8 the following types of checks are used such
as “Typeof value.ngOnDestroy = = = 'function' “.
10. What is in Angular 8?
Ans: Angular 8 introduced a number of new and unique options to runGuardsAndResolvers. In
general, runGuardsAndResolvers is an option which is used for the Angular router configuration
in order to control the resolvers and guards. The first option available in runGuardsAndResolvers
is pathParamsChange. Through, this option router will re-run the guards and resolvers.
Whenever you want to control over the resolvers and guards, use runGuardsAndResolvers option
in Angular 8
AngularJS is an open-source JavaScript framework designed for creating dynamic single web
page applications with fewer lines of code.
By separating DOM manipulation from app logic, it makes code modular and
easy to test.
3. What is the main thing that you would need to change if you were migrating from
AngularJS 1.4 to AngularJS 1.5?
Yes.
Scope
Controller
Model
View
Services
Data Binding
Directives
Filters
Testable
The scope is a unique JavaScript object that plays the role of joining the controller
(JavaScript) with the views (HTML). The controller sets properties on the scope, and the view
binds to them.
7. Explain the concept of scope hierarchy.
Each AngularJS application has only one root scope. Child controllers, however, create scope
for each view. When the new scopes are created, they are added to their parent root scope as
child scopes. This creates a hierarchical structure when they are attached.
Are you a front end developer and looking to enhance your skills? Check out the Angular Training
Course.
8. What is data binding in AngularJS and What is the difference between one-way and two-
way binding?
Data binding is the automatic attunement of data between the view and model components.
AngularJS uses two-way data binding. In one-way binding, the scope variable in the HTML is
set to the first value that its model is assigned to.
In two-way binding, the scope variable changes its value every time its model binds to a
different value.
Directives are unique markers on a DOM element that tell the HTML compiler to attach a
specified behavior to the DOM element. Directives start with ng-prefix. Some of the built-in
directives include ngClass, ngApp, ngRepeat, ngModel, ngBind and ngInit.
Comment directives
Attribute directives
Element directives
During every digest cycle, all new scope model values are compared against the previous
values. This is called dirty checking. If change is detected, watches set on the new model are
fired, and another digest cycle executes. This goes on until all models are stable.
The digest cycle is triggered automatically, but it can be called manually using “.$apply().”
13. What are the common ways of communication between modules of your application,
using core AngularJS functionality?
Using events
Using services
14. Explain what the link function is and how it differs from compile.
The link function combines the directives with a scope to produce a live view.
The link function is responsible for instance DOM manipulation and for registering DOM
listeners.
The compile function is responsible for template DOM manipulation as well as the collection
of all the directives.
15. Explain e2e testing of AngularJS applications.
End-to-end (e2e) testing involves testing an application from start to finish to determine
whether all the components are working correctly. It catches issues within an application
related to integration and flow.
Dependency injection is the process where the dependent objects are injected rather than
being created by the consumer.
SPA is the concept whereby pages are loaded from the server not by doing postbacks, instead
of by creating a single shell page or master page and loading the web pages into the master
page.
Digest cycle time can be decreased by decreasing the number of watchers. To do this, you
can:
Work in batches
Cache DOM