Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
45 views

Angular Interview Questions

Uploaded by

tapasya2097
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Angular Interview Questions

Uploaded by

tapasya2097
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

AngularJS Interview Questions

1. What is Angular?

Angular is a TypeScript-based front-end web application framework. It targets both


the browser and the server. Angular is one of the most popular frameworks for UI
design today, with hundreds of thousands of developers worldwide contributing to
its community project. Its compelling features and performance have made it an
essential tool for any web developer to have in their toolbox. It is maintained by
Google, and its primary function is to design single-page applications. Angular has
significant advantages as a framework, while also providing a
common architecture for developers to work with. It allows developers to create
large, maintainable applications.

2. Why were client-side frameworks like Angular introduced?

Back in the day, web developers used VanillaJS and jQuery to develop dynamic
websites but, as the logic of one's website grew, the code became more and more
tedious to maintain. For applications that use complex logic, developers had to put in
extra effort to maintain the separation of concerns for the app. Also, jQuery did not
provide facilities for data handling across views.

For tackling the above problems, client-side frameworks like Angular came into
the picture, which made life easier for the developers by handling the separation of
concerns and dividing code into smaller bits of information (In the case of Angular,
called Components).

Client-side frameworks allow one to develop advanced web applications like Single-
Page-Application. Not that we cannot develop SPAs using VanillaJS, but by doing
so, the development process becomes slower.

3. How does an Angular application work?

Every Angular app consists of a file named angular.json. This file will contain all the
configurations of the app. While building the app, the builder looks at this file to find
the entry point of the application. Following is an image of the angular.json file:

"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/angular-starter",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": false,
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css",
"src/style.css"
]
}
}

Inside the build section, the main property of the options object defines the entry
point of the application which in this case is main.ts.

The main.ts file creates a browser environment for the application to run, and, along
with this, it also calls a function called bootstrapModule, which bootstraps the
application. These two steps are performed in the following order inside the main.ts
file:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';


platformBrowserDynamic().bootstrapModule(AppModule)

In the above line of code, AppModule is getting bootstrapped.

The AppModule is declared in the app.module.ts file. This module contains


declarations of all the components.

Below is an example of app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';


import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
entryComponents: [],
bootstrap: [AppComponent]
})
export class AppModule { }

As one can see in the above file, AppComponent is getting bootstrapped.

This component is defined in app.component.ts file. This file interacts with the
webpage and serves data to it.

Below is an example of app.component.ts file:


import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular';
}

Each component is declared with three properties:

• Selector - used for accessing the component


• Template/TemplateURL - contains HTML of the component
• StylesURL - contains component-specific stylesheets

After this, Angular calls the index.html file. This file consequently calls the root
component that is app-root. The root component is defined in app.component.ts.
This is how the index.html file looks:

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<app-root></app-root>
</body>
</html>

The HTML template of the root component is displayed inside the <app-root> tags.

This is how every angular application works.

4. What are some of the advantages of Angular over other frameworks?

• Features that are provided out of the box - Angular provides a number of built-in
features like routing, state management, rxjs library and http servicesstraight out of
the box. This means that one does not need to look for the above-stated features
separately. They are all provided with angular.
• Declarative UI - Angular uses HTML to render the UI of an application. HTML is a
declarative language and is much easier to use than JavaScript.
• Long-term Google support - Google announced Long-term support for Angular.
This means that Google plans to stick with Angular and further scale up its
ecosystem.

5. What are the advantages of Angular over React?

Angular vs React: Check out the differences

Angular React

Angular supports bidirectional data binding as React only supports unidirectional


well as mutable data. and immutable data binding.

React allows us to either


The biggest benefit of Angular is that it enables
accomplish it ourselves or with the
dependency injection.
aid of a third-party library.

Angular can be used in both mobile and web React can only be used in UI
development. development only.

Angular features a wide wide range of tools,


In React we can use third-party
libraries, frameworks, plugins, and so on that
libraries for any features.
make development faster and more fun.

Angular uses Typescript. React uses Javascript.

6. List out differences between AngularJS and Angular?

Check out the differences between AngularJS and Angular below. For More
Information, Click here.

Features AngularJS Angular

Architecture AngularJS uses MVC or Model-


View-Controller architecture,
Angular replaces controllers with
where the Model contains the
Components. Components are
business logic, the Controller
nothing but directives with a
processes information and the
predefined template.
View shows the information
present in the Model.
Features AngularJS Angular

Language Angular uses TypeScript language,


which is a statically typed language
AngularJS uses JavaScript and is a superset of JavaScript. By
language, which is a dynamically using statically typed language,
typed language. Angular provides better
performance while developing
larger applications.

Mobile AngularJS does not provide Angular is supported by all popular


Support mobile support. mobile browsers.

Structure While developing larger In the case of Angular, it is easier


applications, the process of to maintain code for larger
maintaining code becomes applications as it provides a better
tedious in the case of AngularJS. structure.

Expression While developing an AngularJS


Whereas in Angular, property
Syntax application, a developer needs to
binding is done using "[ ]" attribute
remember the correct ng-
and event binding is done using "(
directive for binding an event or
)" attribute.
a property.

7. What is the main thing that you would need to change if you were migrating
from AngularJS 1.4 to AngularJS 1.5?

To adapt to the new AngularJS 1.5 components, you would need to


change .directive to .component.

8. Is AngularJS compatible with all browsers?

Yes.

9. What are the key features of AngularJS?

a. Scope

b. Controller

c. Model

d. View

e. Services

f. Data Binding
g. Directives

h. Filters

i. Testable

10. Define scope in AngularJS.

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.

11. 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.

12. In what ways can you use a directive?

You can use a directive as an element, attribute, or class name. To define the way
your directive will be used, you need to set the restrict option in the directive
declaration. The restrict option can be set to:

‘A’ - Only matches attribute name


‘C’ - Only matches class name
‘E’ – Only matches element name

You can combine these restrictions to produce needed results.

13. Explain what a digest cycle is in AngularJS.

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().”

14. What are the common ways of communication between modules of your
application, using core AngularJS functionality?
The common ways of communication include:

a. Using events

b. Using services

c. By assigning models on $rootScope

d. Directly between controllers using ControllerAs and other forms of inheritance

e. Directly between controllers using $parent, $$childHead, $$nextSibling

15. 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.

16. 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.

17. What is dependency injection?

Dependency injection is the process where the dependent objects are injected
rather than being created by the consumer.

18. What are the benefits of dependency injection?

Dependency injection has two significant benefits: Testing and decoupling.

19. What is a Single Page Application (SPA)?

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.
20. How can a SPA be implemented in AngularJS?

SPA can be implemented with Angular by using Angular routes.

21. How can digest cycle time be decreased?

Digest cycle time can be decreased by decreasing the number of watchers. To do


this, you can:

a. Use web worker

b. Work in batches

c. Cache DOM

d. Remove unnecessary watchers

e. Use one-time Angular binding

22. How many types of data bindings are there in AngularJS?


Answer: AngularJS supports both one way and two-way binding.
In one way binding if we change the data model, then there will be no dynamic
change that you will see in view but in two way binding, there will be a dynamic
change whenever a change will be made in the data model.

23) What are the binding directives in AngularJs?


Answer: The binding directives include:
• ng-bind
• ng-bind-html
• ng-bind-template
• ng-non-bindable
• ng-model

24) Explain ng-bind and ng-bind-html directives.


Answer:
ng-bind: It is a directive that replaces the content of the HTML element with the
value of the assigned variable or expression.
The content of the HTML element will change by changing the value of the variable
or expression.

It is like ({{expression}}) and the syntax for this is,

<ANY ELEMENT ng-bind="expression"> </ANY ELEMENT>

ng-bind-html: It is a directive that 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.

25) What is a controller in AngularJS?


Answer: A controller is a JavaScript function that is bound to the specified scope.
Angular instantiates the new controller object and injects the new scope as a
dependency.

26) What are filters in AngularJS?


Answer: The main work of filters is to modify the data, so that it can be merged into
an expression or directive by using a pipe character (it is used for applying filters in
an angular symbol of a pipe which is (|) or this is the symbol).
A filter formats the value of an expression for a display to the user. They can be used
in view templates, controllers, or services, and we can easily create our own filter as
well. A filter is a module provided by AngularJS. There are nine components of a
filter which are provided by it.

Examples: currency, date, filter, JSON, limitTo, etc.

27) What is ng-App directive in AngularJS?


Answer: It is used to define the AngularJs Application. It appoints the root element
of the application and it is kept near the <body> or <html> tag.
We can define any number of ng-app directives inside the HTML document, but only
one AngularJS application can be bootstrapped automatically (auto-bootstrapped)
and the other applications need to be bootstrapped manually.

Example:
<div ng-app="">
<p>My first expression: {{157 + 122}} </p>

</div>

28) What is ng-switch in AngularJS?


Answer: It is used to conditionally exchange the structure of DOM on a template that
is based on a scope-based expression.
This directive lets you show or hide the HTML element depending on the expression.

<element ng-switch="expression">

<element ng-switch-when="value"></element>

29) What is the use of a double-click event in AngularJs?


Answer: It allows you to specify the custom behavior on a double click event of the
mouse on a web page. We can use it (ng-dblclick) as an attribute of the HTML
element like,
<ANY_HTML_ELEMENT ng-dblclick="{expression}">

...

</ANY_HTML_ELEMENT>

30) What are ng-include and ng-click directives in AngularJs?


Answer:
ng-include helps to include different files on the main page. The ng-include directive
includes HTML from an external file.
The included content will be included as child nodes of the specified element. The
value of the ng-include attribute can also be an expression, returning a filename.

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.

31) What is a representational state transfer(REST) in AngularJs?


Answer: REST is an API style that operates over the HTTP request.
The requested URL identifies the data to be operated on, and the HTTP method
identifies the operation that is to be performed. REST is a style of API rather than a
formal specification, and there is a lot of debate and disagreement about what is and
isn’t RESTful, which is a term used to indicate an API that follows the REST style.

AngularJS is flexible about how RESTful web services are consumed.

32) What are the AngularJs Global API?

Answer: It is a combination of global JavaScript function which is used to perform


tasks like comparing objects, iterating objects and converting data.
There are some common API functions like:
• angular. lowercase: It converts a string to lowercase string.
• angular. uppercase: It converts a string to uppercase string.
• angular. isString: It will return true if the current reference is a string.
• angular. isNumber: It will return true if the current reference is a number.

33) What is a provider method in AngularJs?


Answer: A provider is an object which creates a service object by allowing to take
more control.
$get() method is used in the provider which returns the service object. The service
name and the factory function are the arguments that are passed into the provider
method. AngularJS uses $provide to register new providers.

Syntax:
serviceApp.provider("logService", function ())

34) What is Event Handling?


Answer: Event handling in AngularJs is very useful when you want to create
advance AngularJs applications.
We need to handle DOM events like mouse clicks, moves, keyboard presses,
change events and so on. AngularJs has some listener directives like ng-click, ng-
dbl-click, ng-mousedown, ng-keydown, ng-keyup etc.

35) What is AngularJs DOM?


Answer: AngularJs have some directives which are used to encapsulate AngularJs
application data to a disabled attribute of the HTML elements.
Example: ng-disabled directive encapsulates the application data to the disabled
attributes of the HTML DOM element.
<div ng-app="" ng-init="mySwitch=true">

<p>

<button ng-disabled="mySwitch">Click Me!</button>

</p>
<p>

<input type="checkbox" ng-model="mySwitch"/>Button

</p>

<p>

{{ mySwitch }}

</p>

</div>

36) What are the attributes that can be used during the creation of a new
AngularJs directives?
Answer: There are several attributes that 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 in 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.

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.

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.
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 controllers, directive, filters and so on.

40) Explain the advantages of AngularJS.


Answer: Advantages include:
• It supports MVC form.
• Organize two ways of data binding using AngularJS.
• It supports mutual client-server communication.
• It supports simulations.

41) Difference between services and factory.


Answer: Factories are functions that return the object, while services are constructor
functions of the object which is used by a new keyword.
Syntax:
Factory – module.factory(`factoryName`, function);
Service – module.service(`serviceName`, function);

42) If both factory and service are equivalent, then when should I use them?
Answer: Factory provider is preferred using an object, whereas a service provider is
preferred using with class.

43) Difference between AngularJS and React.JS.


Answer: AngularJS is a TypeScript language-based JS framework released in
October 2010 by Google. It is a completely free framework and open source that is
used in SPA projects (i.e. Single Page Application projects).
React.JS is a javascript library developed by Facebook in March 2013 for building
UI. React components can be used on several pages but not as a SPA (i.e. Single
Page Application).

44) Difference between ng-bind and ng-model directive.


Answer: ng-bind directive has one-way data bindings, data flows only from object to
UI, not vice versa (i.e. $scope>>view) and ng-model directive has two-way data
bindings, data flows between UI to object and vice versa(i.e. $scope>>view and
view>>$scope).

45) What is the difference between AJAX and AngularJS?


Answer: AJAX stands for Asynchronous JavaScript and XML which is used for
sending and getting responses from the server without loading the page.
Whereas, AngularJS is a typescript language-based JavaScript framework following
the MVC pattern.
46) Define ng-if, ng-show and ng-hide.
Answer: ng-if directive is used as if clause which removes the HTML element if the
expression becomes false.
Syntax
<element ng-if=”expression”></element>

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>

Both ng-show and ng-hide uses the display property method.

47) What is the difference between ngRoute and ui-router?


Answer: ngRoute is a module developed by angularJS team which was a part of the
core angularJS framework. Whereas ui-router was developed by a third-party
community to overcome the problems of ngRoute.
ngRoute is a location or URL based routing, and ui-router is a state-based routing
which allows nested views.

48) How to set, get and clear cookies in AngularJs?


Answer: AngularJS has a module called ngCookies, so before injecting ngCookies
angular-cookies.js should be included in the application.
• Set Cookies – Put method is used to set cookies in a key-value format.
$cookies.put(“username”, $scope.username);

• Get Cookies – Get method is used to get cookies.


$cookies.get(‘username’);

• Clear Cookies – Remove method is used to remove cookies.


$cookies.remove(‘username’);

49) What is the Global API in AngularJS?

Answer: Global API is the combination of global JavaScript function, which is used to
perform tasks such as comparing objects, iterating objects, and converting the data.

There are a few common API functions like:


o angular.lowercase
It is used to convert a string to lowercase string.
o angular.uppercase
It is used to convert a string to uppercase string.
o angular.IsString
It returns true if the current reference is a string.
o angular.IsNumber
It returns true if the current reference is a number.

50) ''How are AngularJS prefixes $ and $$ used?

Answer: $$ prefix in AngularJS is used as a private variable, as it is responsible for


preventing accidental code collision with the user code.

Whereas, $ prefix is used to define angular core functionalities such as variable,


parameter, property or method, etc.

You might also like