Angular

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 53

Name the building blocks of Angular.

The Angular application is made using the following:

 Modules
 Component
 Template
 Directives
 Data Binding
 Services
 Dependency Injection
 Routing

What is Transpiling in Angular?

Transpiling is the process of converting the typescript into


javascript (using Traceur, a JS compiler). Though typescript is
used to write code in the Angular applications, the code is
internally transpiled into javascript.

Which of the Angular life cycle component execution happens


when a data-bound input value updates?

ngOnChanges is the life cycle hook that gets executed


whenever a change happens to the data that was bound to an
input.

Differentiate between Components and Directives in Angular 5.

Components break up the application into smaller parts;


whereas, Directives add behavior to an existing DOM element

What is the use of @Input and @Output?


When it comes to the communication of Angular Components,
which are in Parent-Child Relationship; we use @Input in Child
Component when we are passing data from Parent to Child
Component and @Output is used in Child Component to receive
an event from Child to Parent Component.

What is ng-content Directive?

The HTML elements like p (paragraph) or h1 (heading) have


some content between the tags. For example, <p>this is a
paragraph</p> and <h1>this is a heading</h1>. Now, similar to
this, what if we want to have some custom text or content
between the angular tags like <app-tax>some tax-related
content</app-tax> This will not work the way it worked for
HTML elements. Now, in such cases, the <ng-content> tag
directive is used.

What does a router.navigate do?

When we want to route to a component we use


router.navigate. Syntax:
this.router.navigate([‘/component_name’]);

What is ViewEncapsulation?

ViewEncapsulation decides whether the styles defined in a


component can affect the entire application or not. There are
three ways to do this in Angular:

Emulated: styles from other HTML spread to the component.

Native: styles from other HTML do not spread to the


component.
None: styles defined in a component are visible to all
components.

What are Services in Angular and what command is used to


create a service?

Services help us in not repeating the code. With the creation of


services, we can use the same code from different
components. command to create a service in angular, ng g
service User (a UserService is created when this command is
used).

What is Dependency Injection in Angular 4?

When a component is dependent on another component the


dependency is injected/provided during runtime.

What is Routing in Angular 5?

Routing helps a user in navigating to different pages using


links.

How to handle Events in Angular 5?

Any activity (button click, mouse click, mouse hover, mouse


move, etc) of a user on a frontend/web screen is termed as an
event. Such events are passed from the view (.HTML) page to a
typescript component (.ts).

What is RouterOutlet?
RouterOutlet is a substitution for templates rendering the
components. In other words, it represents or renders the
components on a template at a particular location.

Explain the usage of {{}}?

The set of brackets {{}} when used with an HTML tag,


represent data from a component. For example, on a HTML
page which has <h1>{{variableName}}</h1>, here the
‘variableName’ is actually typescript (component) data
representing its value on the template; i.e., HTML. This entire
concept is called String Interpolation.

In how many ways the Data Binding can be done?

Data Binding happens between the HTML (template) and


typescript (component). Data binding can be done in 3 ways:

(i) Property Binding (ii) Event Binding (iii) Two-Way Data


Binding.

What is the sequence of Angular Lifecycle Hooks?

OnChange() - OnInit() - DoCheck() - AfterContentInit() -


AfterContentChecked() - AfterViewInit() -
AfterViewChecked() - OnDestroy().

What is the purpose of using package.json in the angular


project?

With the existence of package.json, it will be easy to manage


the dependencies of the project. If we are using typescript in
the angular project then we can mention the typescript
package and version of typescript in package.json.

How is SPA (Single Page Application) technology different from


the traditional web technology?

In traditional web technology, the client requests for a web


page (HTML/JSP/asp) and the server sends the resource (or
HTML page), and the client again requests for another page
and the server responds with another resource. The problem
here is a lot of time is consumed in the requesting/responding
or due to a lot of reloading. Whereas, in the SPA technology,
we maintain only one page (index.HTML) even though the URL
keeps on changing.

What is Component in Angular Terminology?

A web page in Angular has many components involved in it. A


Component is basically a block in which the data can be
displayed on HTML using some logic usually written in
typescript.

What are ngModel and how do we represent it?

ngModel is a directive which can be applied on a text field.


This a two-way data binding. ngModel is represented by [()]

What does a Subscribe method do in Angular 4?

It is a method which is subscribed to an observable. Whenever


the subscribe method is called, an independent execution of
the observable happens.

Differentiate between Observables and Promises.


Observables are lazy, which means nothing happens until a
subscription is made. Whereas Promises are eager; which
means as soon as a promise is created, the execution takes
place. Observable is a stream in which passing of zero or more
events is possible and the callback is called for each event.
Whereas, promise handles a single event.

What is an AsyncPipe in Angular?

When an observable or promise returns something, we use a


temporary property to hold the content. Later, we bind the
same content to the template. With the usage of AsyncPipe,
the promise or observable can be directly used in a template
and a temporary property is not required.

Explain Authentication and Authorization.

Authentication: The user login credentials are passed to an


authenticate API (on the server). On the server side validation
of the credentials happens and a JSON Web Token (JWT) is
returned. JWT is a JSON object that has some information or
attributes about the current user. Once the JWT is given to
the client, the client or the user will be identified with that
JWT.

Authorization: After logging in successfully, the authenticated


or genuine user does not have access to everything. The user
is not authorized to access someone else’s data, he/she is
authorized to access some data.

What is AOT Compilation?

Every angular application gets compiled internally. The angular


compiler takes javascript code, compiles it and produces
javascript code again. Ahead-of-Time Compilation does not
happen every time or for every user, as is the case with Just-
In-Time (JIT) Compilation.

What is Redux?

It is a library which helps us maintain the state of the


application. Redux is not required in applications that are
simple with the simple data flow, it is used in Single Page
Applications that have complex data flow.

What are the Pipes?

This feature is used to change the output on the template;


something like changing the string into uppercase and
displaying it on the template. It can also change Date format
accordingly.

Differentiate between ng-Class and ng-Style.

In ng-Class, loading of CSS class is possible; whereas, in ng-


Style we can set the CSS style.

Why Typescript with Angular?

Typescript is a superset of Javascript. Earlier, Javascript was


the only client-side language supported by all browsers. But,
the problem with Javascript is, it is not a pure Object Oriented
Programming Language. The code written in JS without
following patterns like Prototype Pattern becomes messy and
finally leading to difficulties in maintainability and reusability.
also offer what javascript cannot ie;
 pure OOPS as Typescript offers concepts like Generics,
Interfaces and Types (a Static Typed Language) which
makes it is easier to catch incorrect data types passing
to variables.
 TS provides flexibility to programmers experienced in
java, .net as it offers encapsulation through classes and
interfaces.
 JS version ES5 offers features like Constructor Function,
Dynamic Types, Prototypes. The next version of
Javascript ie ES6 introduced a new feature like Class
keyword but not supported by many browsers.
 TS offers Arrow Functions (=>) which is an ES6 feature
not supported by many browsers directly but when used
in TS, gets compiled into JS ES5 and runs in any browser.
 TS is not the only alternative to JS, we have CoffeeScript,
Dart(Google).
 Finally, it is like, TS makes life easier when compared to
JS.

Why was Angular introduced as a client-side framework?


Traditionally, VanillaJS and jQuery were used by developers to develop dynamic
websites. As the websites became more complex with added features and functionality,
it was hard for the developers to maintain the code. Moreover, there was no provision of
data handling facilities across the views by jQuery. So, Angular was built to address
these issues, thus, making it easier for the developers by dividing code into smaller bits
of information that are known as Components in Angular.
Client-side frameworks permit the development of advanced web applications like SPAs
which, if developed by VanillaJS, is a slower process.

Define the ng-content Directive?


Answer: Conventional HTML elements have some content between the tags. For
instance:

<p>Put your paragraph here</p>

Now consider the following example of having custom text between angular tags:
<app-work>This won’t work like HTML until you use ng-content Directive</app-work>

However, doing so won’t work the way it worked for HTML elements. In order to make it
work just like the HTML example mentioned above, we need to use the ng-content
Directive. Moreover, it is helpful in building reusable components.
Know more about the ng-content directive.

Question: Please explain the various features of Angular.


Answer: There are several features of Angular that make it an ideal front end
JavaScript framework. Most important of them are described as follows:

 Accessibility Applications

Angular allows creating accessible applications using ARIA-enabled components, built-


in a11y test infrastructure, and developer guides.

 Angular CLI

Angular provides support for command-line interface tools. These tools can be used for
adding components, testing, instant deploying, etc.

 Animation Support

Angular’s intuitive API allows the creation of high-performance, complex animation


timelines with very little code.

 Cross-Platform App Development

Angular can be used for building an efficient and powerful desktop, native, and
progressive web apps. Angular provides support for building native mobile applications
using Cordova, Ionic, or NativeScript.
Angular allows creating high performance, offline, and zero-step installation progressive
web apps using modern web platform capabilities. The popular JS framework can also
be used for building desktop apps for Linux, macOS, and Windows.

 Code Generation

Angular is able to convert templates into highly-optimized code for modern JavaScript
virtual machines.

 Code Splitting
With the new Component Router, Angular apps load quickly. The Component Router
offers automatic code-splitting so that only the code required to render the view that is
requested by a user is loaded.

 Synergy with Popular Code Editors and IDEs

Angular offers code completion, instant errors, etc. with popular source code editors and
IDEs.

 Templates

Allows creating UI views with a simple and powerful template syntax.

 Testing

Angular lets you carry out frequent unit tests using Karma. The Protractor allows
running faster scenario tests in a stable way.

State some advantages of Angular over other frameworks.


Answer:
Out of box Features: Several built-in features like routing, state management, rxjs
library, and HTTP services are straight out of the box services provided by Angular. So,
one does not need to look for the above-stated features separately.
Declarative UI: Angular uses HTML to render the UI of an application as it is a
declarative language and is much easier to use than JavaScript.
Long-term Google Support: Google plans to stick with Angular and further scale up its
ecosystem as it has offered its long term support to Angular.

What is the difference between Angular and AngularJS.


Answer:

Parameters AngularJS Angular

MVC or Model-View-Controller architecture


facilitates the AngularJS framework, where
Angular replaces controllers with
the Model contains the business logic and
Architecture Components that are directives with
Controllers processes information, lastly,
a predefined template.
View shows the information present in the
Model.
Angular uses TypeScript language,
a statically typed language, and a
AngularJS uses JavaScript language, which
Language superset of JavaScript. Angular
is a dynamically typed language.
provides better performance while
developing larger applications.

Supported by all popular mobile


Mobile Support Does not support mobile support.
browsers.

It is easier to maintain code for


The process of maintaining code becomes
Structure larger applications as it provides a
tedious in the case of larger applications.
better structure.

A developer needs to remember the correct Property binding is done using "[ ]"
Expression Syntax ng-directive for binding an event or a attribute and event binding is done
property. using "( )" attribute.

Routing AngularJS uses $routeprovider.when() Angular uses @RouteConfig{(…)}

The development effort and time are


Angular is faster due to upgraded
Speed reduced significantly because of the two-
features.
way data binding

Angular supports a hierarchical


Dependency Injectio Dependency Injection with
AngularJS doesn’t support DI.
n unidirectional tree-based change
detection.

Angular has active support with


No official support or updates are available
Support updates rolling out every now and
for AngularJS.
then.

What are Lifecycle hooks in Angular? Explain some life cycles hooks
Answer: Angular components enter its lifecycle from the time it is created to the time it
is destroyed. Angular hooks provide ways to tap into these phases and trigger changes
at specific phases in a lifecycle.
ngOnChanges( ): This method is called whenever one or more input properties of the
component changes. The hook receives a SimpleChanges object containing the
previous and current values of the property.
ngOnInit( ): This hook gets called once, after the ngOnChanges hook.
It initializes the component and sets the input properties of the component.
ngDoCheck( ): It gets called after ngOnChanges and ngOnInit and is used to detect
and act on changes that cannot be detected by Angular.
We can implement our change detection algorithm in this hook.
ngAfterContentInit( ): It gets called after the first ngDoCheck hook. This hook
responds after the content gets projected inside the component.
ngAfterContentChecked( ): It gets called after ngAfterContentInit and every
subsequent ngDoCheck. It responds after the projected content is checked.
ngAfterViewInit( ): It responds after a component's view, or a child component's view is
initialized.
ngAfterViewChecked( ): It gets called after ngAfterViewInit, and it responds after the
component's view, or the child component's view is checked.
ngOnDestroy( ): It gets called just before Angular destroys the component. This hook
can be used to clean up the code and detach event handlers.

Could we make an angular application to render on the server-side?


Yes, we can, with Angular Universal, a technology provided by Angular capable of
rendering applications on the server-side.
The benefits of using Angular Universal are:

 Better User Experience: Allows users to see the view of the application instantly.
 Better SEO: Universal ensures that the content is available on every search engine
leading to better SEO.
 Loads Faster: Render pages are available to the browsers sooner, so the server-side
application loads faster.

Explain Dependency Injection?


Answer: Dependency injection is an application design pattern that is implemented by
Angular and forms the core concepts of Angular.
Let us understand in a detailed manner. Dependencies in Angular are services which
have a functionality. Various components and directives in an application can need
these functionalities of the service. Angular provides a smooth mechanism by which
these dependencies are injected into components and directives.

Describe the MVVM architecture.


Answer: MVVM architecture removes tight coupling between each component. The
MVVM architecture comprises of three parts:

 Model
 View
 ViewModel

The architecture allows the children to have reference through observables and not
directly to their parents.

 Model: It represents the data and the business logic of an application, or we may
say it contains the structure of an entity. It consists of the business logic - local
and remote data source, model classes, repository.
 View: View is a visual layer of the application, and so consists of the UI Code(in
Angular- HTML template of a component.). It sends the user action to the
ViewModel but does not get the response back directly. It has to subscribe to the
observables which ViewModel exposes to it to get the response.
 ViewModel: It is an abstract layer of the application and acts as a bridge
between the View and Model(business logic). It does not have any clue which
View has to use it as it does not have a direct reference to the View. View and
ViewModel are connected with data-binding so, any change in the View the
ViewModel takes note and changes the data inside the Model. It interacts with
the Model and exposes the observable that can be observed by the View.

Demonstrate navigating between different routes in an Angular


application.
Answer: Following code demonstrates how to navigate between different routes in an
Angular app dubbed “Some Search App”:

import from "@angular/router";


.
.
.
@Component({
selector: 'app-header',
template: `
<nav class="navbar navbar-light bg-faded">
<a class="navbar-brand" (click)="goHome()">Some Search App</a>
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link" (click)="goHome()">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" (click)="goSearch()">Search</a>
</li>
</ul>
</nav>
`
})
class HeaderComponent {
constructor(private router: Router) {}
goHome() {
this.router.navigate(['']);
}
goSearch() {
this.router.navigate(['search']);
}
}

What is the AOT (Ahead-Of-Time) Compilation? What are its


advantages?
Answer: An angular application consists of components and templates which a
browser cannot understand. Therefore, every Angular application needs to be compiled
before running inside the browser. The Angular compiler takes in the JS code, compiles
it, and then produces some JS code. It is known as AOT compilation and happens only
once per occasion per user.
There are two kinds of compilation that Angular provides:
JIT(Just-in-Time) compilation: the application compiles inside the browser during
runtime
AOT(Ahead-of-Time) compilation: the application compiles during the build time.
Advantages of AOT compilation:

 Fast Rendering: The browser loads the executable code and renders it immediately as
the application is compiled before running inside the browser.
 Fewer Ajax Requests: The compiler sends the external HTML and CSS files along with
the application, eliminating AJAX requests for those source files.
 Minimizing Errors: Easy to detect and handle errors during the building phase.
 Better Security: Before an application runs inside the browser, the AOT compiler adds
HTML and templates into the JS files, so there are no extra HTML files to be read, thus
providing better security for the application.
Could you explain services in Angular?
Singleton objects in Angular that get instantiated only once during the lifetime of an
application are called services. An Angular service contains methods that maintain the
data throughout the life of an application.
The primary intent of an Angular service is to organize as well as share business logic,
models, or data and functions with various components of an Angular application.
The functions offered by an Angular service can be invoked from any Angular
component, such as a controller or directive.

Discuss the advantages and disadvantages of using Angular?


Answer: Following are the various advantages of using Angular:

 Ability to add a custom directive


 Exceptional community support
 Facilitates client and server communication
 Features strong features, such as Animation and Event Handlers
 Follows the MVC pattern architecture
 Offers support for static template and Angular template
 Support for two-way data-binding
 Supports dependency injection, RESTful services, and validations

Disadvantages of using Angular are enumerated as follows:

 Complex SPAs can be inconvenient and laggy to use due to their size
 Dynamic applications do not always perform well
 Learning Angular requires a decent effort and time

Enumerate some salient features of Angular 7.


Answer: Unlike the previous versions of Angular, the 7th major release comes with
splitting in @angular/core. This is done in order to reduce the size of the same.
Typically, not each and every module is required by an Angular developer. Therefore, in
Angular 7 each split of the @angular/core will have no more than 418 modules.
Also, Angular 7 brings drag-and-drop and virtual scrolling into play. The latter enables
loading as well as unloading elements from the DOM. For virtual scrolling, the latest
version of Angular comes with the package. Furthermore, Angular 7 comes with a new
and enhanced version of the ng-compiler.
Question: What is string interpolation in Angular?
Answer: Also referred to as moustache syntax, string interpolation in Angular refers to
a special type of syntax that makes use of template expressions in order to display the
component data. These template expressions are enclosed within double curly braces
i.e. {{ }}.
The JavaScript expressions that are to be executed by Angular are added within the
curly braces and the corresponding output is embedded into the HTML code. Typically,
these expressions are updated and registered like watches as a part of the digest cycle.

Question: Explain Angular Authentication and Authorization.


Answer: The user login credentials are passed to an authenticate API, which is present
on the server. Post server-side validation of the credentials, a JWT (JSON Web Token)
is returned. The JWT has information or attributes regarding the current user. The user
is then identified with the given JWT. This is called authentication.
Post logging-in successfully, different users have a different level of access. While some
may access everything, access for others might be restricted to only some resources.
The level of access is authorization.
Here is a detailed post on Angular 7 - JWT Authentication Example & Tutorial:
http://jasonwatmore.com/post/2018/11/16/angular-7-jwt-authentication-example-tutorial

Question: Can you explain the concept of scope hierarchy in Angular?


Answer: Angular organizes the $scope objects into a hierarchy that is typically used by
views. This is known as the scope hierarchy in Angular. It has a root scope that can
further contain one or several scopes called child scopes.
In a scope hierarchy, each view has its own $scope. Hence, the variables set by a
view’s view controller will remain hidden to other view controllers. Following is a typical
representation of a Scope Hierarchy:

 Root $scope
o $scope for Controller 1
o $scope for Controller 2
o …
o ..
o .
o $scope for Controller n

Question: How to generate a class in Angular 7 using CLI?


Answer:

ng generate class Dummy [options]


This will generate a class named Dummy.

Question: Explain what is the difference between Angular


and backbone.js?
Answer: Following are the various notable differences between Angular and
Backbone.js

 Architecture

Backbone.js makes use of the MVP architecture and doesn’t offer any data binding
process. Angular, on the contrary, works on the MVC architecture and makes use of
two-way data binding for driving application activity.

 Community Support

Being backed by Google greatly ups the community support received by the Angular
framework. Also, extensive documentation is available. Although Backbone.js has a
good level of community support, it only documents on Underscore.js templates, not
much else.

 Data Binding

Angular uses two-way data binding process and thus is a bit complex. Backbone.js, on
the contrary, doesn’t have any data binding process and thus, has a simplistic API.

 DOM

The prime focus of Angular JS is upon valid HTML and dynamic elements that imitate
the underlying data for rebuilding the DOM as per the specified rules and then works on
the updated data records.
Backbone.js follows the direct DOM manipulation approach for representing data and
application architecture changes.

 Performance

Thanks to its two-way data binding functionality, Angular offers an impactful


performance for both small and large projects.
Backbone.js has a significant upper hand in performance over Angular in small data
sets or small webpages. However, it is not recommended for larger webpages or large
data sets due to the absence of any data binding process.

 Templating

Angular supports templating via dynamic HTML attributes. These are added to the
document to develop an easy to understand application at a functional level. Unlike
Angular, Backbone.js uses Underscore.js templates that aren’t fully-featured as Angular
templates.

 The Approach to Testing

The approach to testing varies greatly between Angular and Backbone.js due to the fact
that while the former is preferred for building large applications the latter is ideal for
developing smaller webpages or applications.
For Angular, unit testing is preferred and the testing process is smoother through the
framework. In the case of Backbone.js, the absence of a data binding process allows for
a swift testing experience for a single page and small applications.

 Type

Angular is an open-source JS-based front-end web application framework that extends


HTML with new attributes. On the other hand, Backbone.js is a lightweight JavaScript
library featuring a RESTful JSON interface and MVP framework.

Question: How do Observables differ from Promises?


Answer: As soon as a promise is made, the execution takes place. However, this is not
the case with observables because they are lazy. This means that nothing happens until
a subscription is made. While promises handle a single event, observable is a stream
that allows passing of more than one event. A callback is made for each event in an
observable.

Question: Please explain the difference between Angular and


AngularJS?
Answer: Various differences between Angular and AngularJS are stated as follows:

 Architecture - AngularJS supports the MVC design model. Angular relies on


components and directives instead
 Dependency Injection (DI) - Angular supports a hierarchical Dependency Injection
with unidirectional tree-based change detection. AngularJS doesn’t support DI
 Expression Syntax - In AngularJS, a specific ng directive is required for the image or
property and an event. Angular, on the other hand, use () and [] for blinding an event and
accomplishing property binding, respectively
 Mobile Support - AngularJS doesn’t have mobile support while Angular does have
 Recommended Language - While JavaScript is the recommended language for
AngularJS, TypeScript is the recommended language for Angular
 Routing - For routing, AngularJS uses $routeprovider.when() whereas Angular uses
@RouteConfig{(…)}
 Speed - The development effort and time are reduced significantly thanks to support for
two-way data binding in AngularJS. Nonetheless, Angular is faster thanks to upgraded
features
 Structure - With a simplified structure, Angular makes the development and
maintenance of large applications easier. Comparatively, AngularJS has a less
manageable structure
 Support - No official support or updates are available for the AngularJS. On the
contrary, Angular has active support with updates rolling out every now and then

Question: Observe the following image:

What should replace the “?”?


Directives. The image represents the types of directives in Angular; Attribute, structural,
and custom.

Question: Could you explain the concept of templates in Angular?


Written with HTML, templates in Angular contains Angular-specific attributes and
elements. Combined with information coming from the controller and model, templates
are then further rendered to cater the user with the dynamic view.

Explain the difference between an Annotation and a Decorator in


Angular?
In Angular, annotations are used for creating an annotation array. They are only
metadata set of the class using the Reflect Metadata library.
Decorators in Angular are design patterns used for separating decoration or
modification of some class without changing the original source code.
What are directives in Angular?
Directives are one of the core features of Angular. They allow an Angular developer to
write new, application-specific HTML syntax. In actual, directives are functions that are
executed by the Angular compiler when the same finds them in the DOM. Directives are
of three types:

 Attribute Directives
 Component Directives
 Structural Directives

Question: What are the building blocks of Angular?


Answer: There are essentially 9 building blocks of an Angular application. These are:

1. Components – A component controls one or more views. Each view is some specific
section of the screen. Every Angular application has at least one component, known as
the root component. It is bootstrapped inside the main module, known as the root
module. A component contains application logic defined inside a class. This class is
responsible for interacting with the view via an API of properties and methods.
2. Data Binding – The mechanism by which parts of a template coordinates with parts of a
component is known as data binding. In order to let Angular know how to connect both
sides (template and its component), the binding markup is added to the template HTML.
3. Dependency Injection (DI) – Angular makes use of DI to provide required
dependencies to new components. Typically, dependencies required by a component
are services. A component’s constructor parameters tell Angular about the services that
a component requires. So, a dependency injection offers a way to supply fully-formed
dependencies required by a new instance of a class.
4. Directives – The templates used by Angular are dynamic in nature. Directives are
responsible for instructing Angular about how to transform the DOM when rendering a
template. Actually, components are directives with a template. Other types of
directives are attribute and structural directives.
5. Metadata – In order to let Angular know how to process a class, metadata is attached to
the class. For doing so decorators are used.
6. Modules – Also known as NgModules, a module is an organized block of code with a
specific set of capabilities. It has a specific application domain or a workflow. Like
components, any Angular application has at least one module. This is known as the root
module. Typically, an Angular application has several modules.
7. Routing – An Angular router is responsible for interpreting a browser URL as an
instruction to navigate to a client-generated view. The router is bound to links on a page
to tell Angular to navigate the application view when a user clicks on it.
8. Services – A very broad category, a service can be anything ranging from a value and
function to a feature that is required by an Angular app. Technically, a service is a class
with a well-defined purpose.
9. Template – Each component’s view is associated with its companion template. A
template in Angular is a form of HTML tags that lets Angular know that how it is meant to
render the component.
Please explain the differences between Angular and jQuery?
Answer: The single biggest difference between Angular and jQuery is that while the
former is a JS frontend framework, the latter is a JS library. Despite this, there are some
similarities between the two, such as both features DOM manipulation and provides
support for animation.
Nonetheless, notable differences between Angular and jQuery are:

 Angular has two-way data binding, jQuery does not


 Angular provides support for RESTful API while jQuery doesn’t
 jQuery doesn’t offer deep linking routing though Angular supports it
 There is no form validation in jQuery whereas it is present in Angular

Could you explain the difference between Angular expressions and


JavaScript expressions?
Although both Angular expressions and JavaScript expressions can contain literals,
operators, and variables, there are some notable dissimilarities between the two.
Important differences between Angular expressions and JavaScript expressions are
enlisted below:

 Angular expressions support filters while JavaScript expressions do not


 It is possible to write Angular expressions inside the HTML tags. JavaScript expressions,
contrarily, can’t be written inside the HTML tags
 While JavaScript expressions support conditionals, exceptions, and loops, Angular
expressions don’t

Question: Can you give us an overview of Angular architecture?


Answer: You can draw some like this:
Here is Angular Architecture in detail: https://angular.io/guide/architecture

What is Angular Material?


It is a UI component library. Angular Material helps in creating attractive, consistent, and
fully functional web pages as well as web applications. It does so while following
modern web design principles, including browser portability and graceful degradation.

Question: What is AOT (Ahead-Of-Time) Compilation?


Answer: Each Angular app gets compiled internally. The Angular compiler takes in the
JS code, compiles it and then produces some JS code. This happens only once per
occasion per user. It is known as AOT (Ahead-Of-Time) compilation.

What is Data Binding? How many ways it can be done?


In order to connect application data with the DOM (Data Object Model), data binding is
used. It happens between the template (HTML) and component (TypeScript). There are
3 ways to achieve data binding:

1. Event Binding – Enables the application to respond to user input in the target
environment
2. Property Binding – Enables interpolation of values computed from application data into
the HTML
3. Two-way Binding – Changes made in the application state gets automatically reflected in
the view and vice-versa. The ngModel directive is used for achieving this type of data
binding.
Question: What is demonstrated by the arrow in the following image?

Answer: This represents a dependency injection or DI.

Question: Can you draw a comparison between the service() and the
factory() functions?
Answer: Used for the business layer of the application, the service() function operates
as a constructor function. The function is invoked at runtime using the new keyword.
Although the factory() function works in pretty much the same way as the service()
function does, the former is more flexible and powerful. In actual, the factory() function
are design patterns that help in creating objects.

Question: Please explain the digest cycle in Angular?


Answer: The process of monitoring the watchlist in order to track changes in the value
of the watch variable is termed the digest cycle in Angular. The previous and present
versions of the scope model values are compared in each digest cycle.
Although the digest cycle process gets triggered implicitly, it is possible to start it
manually by using the $apply() function.

Question: Could you explain the various types of filters in AngularJS.


Answer: In order to format the value of expression so that it can be displayed to the
user, AngularJS has filters. It is possible to add these filters to the controllers, directives,
services, or templates. AngularJS also provides support for creating custom filters.
Organizing data in such a way so that it is displayed only when certain criteria are
fulfilled is made possible using filters. Filters are added to the expressions using the
pipe ‘|’ character. Various types of AngularJS filters are enumerated as follows:

 currency – Formats a number to the currency format


 date – Formats a data to some specific format
 filter – Selects a subset of items from an array
 json – Formats an object to a JSON string
 limitTo – Limits an array or string into a specified number of characters or elements
 lowercase – Formats a string to lowercase
 number – Formats a number to a string
 orderBy – Orders an array by an expression

Question: What is new in Angular 6?


Answer: Here are some of the new aspects introduced in Angular 6:

 Angular Elements – It allows converting Angular components into web components and
embeds the same in some non-Angular application
 Tree Shakeable Provider – Angular 6 introduces a new way of registering a provider
directly inside the @Injectable() decorator. It is achieved by using the providedIn
attribute
 RxJS 6 – Angular 6 makes use of RxJS 6 internally
 i18n (internationalization) – Without having to build the application once per locale, any
Angular application can have “runtime i18n”

Question: What is ngOnInit()? How to define it?


Answer: ngOnInit() is a lifecycle hook that is called after Angular has finished initializing
all data-bound properties of a directive. It is defined as:

Interface OnInit {

ngOnInit() : void

Question: What is SPA (Single Page Application) in Angular? Contrast SPA


technology with traditional web technology?
Answer: In the SPA technology, only a single page, which is index.HTML, is maintained
although the URL keeps on changing. Unlike traditional web technology, SPA
technology is faster and easy to develop as well.
In conventional web technology, as soon as a client requests a webpage, the server
sends the resource. However, when again the client requests for another page, the
server responds again with sending the requested resource. The problem with this
technology is that it requires a lot of time.

Question: What is the code for creating a decorator?


Answer: We create a decorator called Dummy:

function Dummy(target) {
dummy.log('This decorator is Dummy', target);

Question: What is the process called by which TypeScript code is


converted into JavaScript code?
Answer: It is called Transpiling. Even though TypeScript is used for writing code in
Angular applications, it gets internally transpiled into equivalent JavaScript.

Question: What is ViewEncapsulation and how many ways are there do


to do it in Angular?
Answer: To put simply, ViewEncapsulation determines whether the styles defined in a
particular component will affect the entire application or not. Angular supports 3 types of
ViewEncapsulation:

 Emulated – Styles used in other HTML spread to the component


 Native – Styles used in other HTML doesn’t spread to the component
 None – Styles defined in a component are visible to all components of the application

Question: Why prioritize TypeScript over JavaScript in Angular?


Answer: TypeScript is a superset of Javascript as it is Javascript + Types or extra
features like typecasting for variables, annotations, variable scope and much more. The
typescript is designed in a way to overcome Javascript shortcomings like typecasting of
variables, classes, decorators, variable scope and many more. Moreover, Typescript is
purely object-oriented programming that offers a "Compiler" that can convert to
Javascript-equivalent code.

Question: Discuss the lifecycle designed for directive and components


in Angular JS especially for the newly introduced version 6.0?
Answer:
Components and directive of Angular JS follow the following typical lifecycle.

 nhOnInit
 ngDoCheck
 ngOnDestroy
 Constructor
 ngOnChanges
 ngAfterContentInit (only for components)
 ngAfterContentChecked (only for components)
 ngAfterViewInit (only for components)
 ngAfterViewChecked (only for components)
Question: Write the features for Angular 6 over Angular 5.
Answer: Following are the features:
1. Added ng update
CLI command updates angular project dependencies to their latest versions. The ng
update is a normal package manager tool to identify and update in normal package
manager tools to identify and update other dependencies.
2. Uses RxJS6
This is the third party library (RxJS) and introduces two important changes as compared
to RxJS5.

1. Introduces a new internal package structure.


2. Operator concept

To update of RxJS6, run the following command:

npm install --save rxjs@6

To update your existing Angular Project, run the following:

npm install --save rxjs-compat

3. The <ng-template>
Angular 6 uses <ng-template> instead of <template>
4. Service Level Changes
If in an earlier version, the user wanted to provide a service to the entire application, the
user was required to add it to providers in the AppModule but it is not required in the
case of Angular6.
5. Renamed Operators
Angular 6 has renamed following operators:

 do() => tap()


 catch() => catchError()
 finally() => finalize()
 switch()=>switchAll()
 throw() => throwError
Why Angular?
Now comes the critical question.
Angular comes with a host of benefits and features that are apt for
enterprise applications and websites that have a lot of dynamic content or
multiple workflows. Whether it is exhaustive documentation, or the
extensive support by Google, or component-based architecture (from
version 2), Angular has all you can ask for from a web development
framework. Some reasons why you should use Angular are –

 Great support by Google, thus making the platform user-friendly and


trustworthy.
 A component-based architecture where the application is divided into
functional and logical components that are independent of each
other. Parts can be decoupled, replaced, or reused easily. This type of
architecture also ensures easier testing at each stage.
 A lot of reusable code and third-party components are available, thus
improving productivity.
 The code is rendered faster because it gets converted from
TypeScript (or HTML) to JavaScript during the build process itself.
This is called the Ahead-of-Time (AOT) compilation.
 Command Line Interface (CLI) – CLI facilitates development in the
most efficient way. You can create a new project, add your
functionalities, and test them quickly. Further, initialization and
configuration become easy too.
 Angular six allows adding custom elements to web apps built with
other environments like React, Vue, jQuery, etc.…
 Angular six also included an Ivy renderer that translates components
and templates into JavaScript by rendering. During the process, any
unused code is removed, thus making web apps load faster.
 Angular Universal that is used for server-side rendering, helps
increase the number of users on the website and faster loading of
pages.
 Excellent documentation and support community
What Is the Purpose of Angular?
Answer: The purpose of using Angular is to create fast, dynamic, and
scalable web applications with ease, using components and directives.

What Is Angular/What Do You Know About


Angular?
Angular is an open-source, front-end web development framework based
on TypeScript. It is most suited for developing enterprise web applications
because the code is reusable and maintainable. Angular started as a SPA
(Single-Page-Application) framework and now supports dynamic content
based on different users through dependency injection. YouTubeTV is the
most popular company that uses Angular

Mention Some of the Features of Angular


Answer: Some important features are –

 Component-based architecture – applications are written as a set of


independent components.
 Parts can be created, tested, integrated using Angular CLI.
 Great support for complex animations without writing much code.
 Because of the component router, Angular supports automatic code-
splitting. Hence only the code required to render a particular view is
loaded.
 Cross-platform application development.
 Template syntax for creating UI views.

What Is Angular CLI? How Do You Use It?


Answer: Angular CLI automates the end-to-end development process. The
app's initialization, configuration, and development process become
straightforward and easy. With a CLI (Command Line Interface), we can
create a new project, add new features, and run tests (unit tests and end-to-
end tests) by just typing a few simple commands. This way, development
and testing processes both become faster.
For example,
To create a new application, we should type –
ng new <appname> [options]
2
to create a class using CLI (in Angular 7), we have to type –
3
ng generate class MySampleClass [options]
4
to generate a component,
5
ng g c <componentname>

What Are Directives in Angular?


Answer: With directives, developers can write application-specific custom
HTML syntax. The new language is written in the DOM, and the Angular
compiler executes the directive functions when it finds a new HTML syntax.
There are three types of directives – attribute, component, structural.

Question: Mention an Example of the Structural Directive


Answer: Structural directives change the structure of DOM. Examples, *ngIf
and *ngFor. Usage example.
<div *ngIf = “product” class=”name”>{{product.name}}</div>

Same way.
<ul> <li *ngFor = “Show product list”>{{product.name}}</li>
</ul>
How Is Dependency Injection (DI) Done in
Angular?
In Angular, a class asks for services or objects when it is instantiated, which
means if a class is invoked, it doesn’t create any objects, rather it depends
on an external source to instantiate objects, services, or parameters. In this
process, an injectable service is created and registered. Injectors can be
configured in three different ways,

 @Injectable() decorator for the service.


 @NgModule for NgModule.
 @Component for the component.

What Are Templates in Angular?


Answer: The template is simply an HTML view where binding controls can
display data to the properties of the Angular component. Templates can be
defined inline using the template property as –
Template:
<div>My sample Template</div>

Or can be called from a different HTML file by using @Component


decorator’s URL property –
templateUrl: 'app/app.component.html'

Question: How Are Angular Expressions


Different From Javascript Expressions?
Answer: Both are similar and can have operators, variables, and literals.
However, some differences between both are –

Angular expressions JavaScript expressions


Conditions, exceptions, and loops (control statements) cannot
All the control statements can be used
be used

Regular expressions cannot be used Regex is widely used

Filters can be used within the expression itself so that data is


Such a concept doesn’t exist
formatted before being displayed

Expressions are evaluated against a scope object Expressions are evaluated against the global wind

If there are issues in evaluating an expression or


Expression evaluation forgives to undefined or null
generates ReferenceError or TypeError.

Functions cannot be declared Any number of functions can be declared

New, comma, bitwise, void operators cannot be used. These are possible

You can mention any 3-4 to the examiner. If they specifically ask, you can
say that particular point of difference.

Question: Explain the Architecture of


Angular
Answer: As we have seen in Question 2, Components, modules, templates,
etc. are the main building blocks of Angular. All of these are again based on
NgModules, which provide compilation context for components. When
asked in the interview, you can talk about the essential building blocks and
then draw the following diagram (source: angular documentation) to depict
the relationship between each –
You can see that the view is contained in the template, and properties are
bound from components to the template. The DI services are injected by
the injector into the parts as required. Directives are added to the model.
Modules contain the core logic like services, values, functions, and
components.
Some Differences Between Component and
Directive
Answer: The component is a specific type of directive, that has a view.

Component Directive

@Directive is used to register


To register component, Annotation used is @Component
a directive

The primary purpose of ingredients is to break the complex Purpose of the `directive is to
application into smaller, more manageable parts
(components) create new custom components that are reusable

Any number of directives can be used in one


Each DOM element can have only one component
DOM element

Component mandatorily requires @View decorator,


A directive has nothing to do with views
template, or template URL to specify the view.

Question: What Is the Primary Language


Used in Angular?
Answer: Angular is based on TypeScript and HTML. HTML is used for the
template, and TypeScript (a superset of JavaScript) is used for components.

What Is Data Binding, and What Are the


Different Categories of Data Binding?
Answer: Data binding is used to connect the application data and DOM i.e.
components with the template. They can be categorized based on the
direction of the data flow.

Data flow Direction Type Description


From source to view Interpolation - Attribute,
Interpolates values calculated from application data int
(one-way) style, class, property

From lightview to the


Event Enables applications to respond to users in the target e
source (one-way)

View-source-view (two- Changes in the application state automatically get refle


Two-way
way) and vice-versa. For this type of binding, ngModel direc

Explain the Differences Between One-Way


Binding and Two-Way Binding
Answer:

One-way binding Two-way binding

The view doesn’t change or update automatically UI or view is continuously updated automatically as the
whenever there is a change in the data model.
data model changes. The process is similar to the
Custom code needs to be manually written to reflect
changes. synchronization process.

What Are the Various Filters Supported by


Angular?
Answer:

Filter name Description

Uppercase Convert string to uppercase

Lowercase Convert string to lowercase

Date Convert date to the specified format


Currency Convert the number to currency format

Number Format number into a string

Orderby Orders an array by specific expression

limitTo Limits array into the specified number of elements; string to specified number of characters

JSON Format object to JSON string

Filter A select a subset of items from the array

You can mention few of them and show an example as well –


<p>Amount: {{ amount | currency }}</p>

What Are Ngmodules? Differentiate Between


Javascript Modules and Ngmodules
NgModule was introduced after Angular 2, to enable developers to declare
all the relationships in one place with metadata. Thus, in short, NgModules
are built from metadata that describes components, services, directives,
pipes etc… Angular then creates a component factory, a class that creates
components.
Difference between JS modules and NgModules –

JS modules NgModules

Bounds all the classes Bounds only declarable classes

All the member classes are defined in a


The module’s classes are listed in the @NgModule.declarations list
single file
Cant extend the entire application with The entire application can be extended with services using @NgModu
services add providers

It can import or export only those declarable classes that it owns or im


Can import or export any kind of classes
modules.

Question: What Are ngIf and ngFor? Can You


Show a Small Example to Use Them?
Answer: Just like if and for in other languages, ngIf and ngFor are used as
control statements. Example –
<p *ngIf="display">Show this only if the Boolean "display" is true</p>
Where the display is a boolean with the value true or false. Learn
more about ngIf.
ngFor is used to loop through and display elements of an array (set of data).
<tr *ngFor="let student of students; let i = index">
<td>{{student.name}}

</td> <td>{{i}}</td> </tr>

The second part (i=index) is optional and only needed if you want to
display the index.

Question: Which Is the Latest Version of


Angular? What Are the New Features in It?
Answer: The latest version is Angular 8. Some features are –

 Support for TypeScript 3.4.


 Dynamic import for lazy routes.
 Web workers.
 Differential loading for application code.
 Introduction of Angular Ivy – improved payload size, backward
compatibility, faster re-build time, easier debugging etc…
Question: What Is a Component?
Answer: The component is a logical piece of code. The component consists
of the template (that contains the HTML (or URL) that needs to be
rendered), class (class that defines properties and methods that supports
the view) and metadata (defined using decorator).
Example –
@Component ({ selector: 'my-app', template: ` <div>
<h1>{{appTitle}}</h1>

<div>What is your name?</div> </div>, })

Question: Is There a Way to Convert the


Typescript Code Into Javascript Code? How
Is It Done?
Answer: Yes, converting TypeScript into JavaScript is called as
transpilation.

Question: What Is the Digest Cycle?


Answer: Digest cycle is the process of monitoring watchlist to track the
changes in the value of the watch variable. The digest cycle is implicitly
triggered, but we can also trigger it manually using $apply() function.

Question: What Is a Pipe? Write a Simple


Code to Demonstrate.
Answer: Pipe (|) is used to transform input data into desired format. For
example,
<p>Price is {{ price | currency }}</p>

Can You Create a Parameterized Pipe in the


Above Example?
Yes,
<p>Price is {{ price | currency : “USD$” : 0.00 }}</p>

Question: Explain How You Can Chain Pipes


Answer: We can add any number of filters using pipes -
<p>Average is {{ average | uppercase | number}}</p>

Is It Possible to Create a Custom Pipe?


How?
Answer: Yes, we can create custom pipes.

 Pipe metadata @Pipe decorator can be imported from core Angular


library
 Pipe is a class that is decorated with the above metadata
(@Pipe({name: 'myCustomPipe'}))
 The next step is to define the transformation. For this, the pipe class
should implement the method transform() of the PipeTransform
class.
 Specify the pipe name in the main code

<p>Size: {{number | myCustomPipe: 'Error'}}</p>

Question: What Is the Purpose of an Async


Pipe?
Answer: Async pipe subscribes to a promise or an observable, and returns
the latest value. If a new value is emitted, the pipe marks the component
that needs to be checked for any changes.
<code>observable|async</code>

What Is the Difference Between Pure and


Impure Pipe?
Answer:

Pure pipe Impure pipe


Can produce different output for the same input based on
Doesn’t get affected by internal state
the internal state

Can be shared with many different It cannot be shared because the internal state can be affected
instances by any factors.

Explain the Importance of HttpClient.


Answer: HttpClient is a simplified Http API for Angular applications. It
gives better observable APIs, better error handling mechanisms, testability,
request and response interception, typed request and response objects.
The HttpClientAPI rests on the XMLHttpRequest interface exposed by the
browsers.

How Does Angular Router Work?


Answer: Angular router interprets a browser URL as commands to
navigate to a client-generated view. The router is bound to the links on a
page. This way Angular knows to navigate the application view to the
required page when a user clicks on it.

What Are the Router Navigation Events?


Answer: Router navigation events help track the lifecycle of a route. These
are –

 NavigationStart,
 RouteConfigLoadStart,
 RouteConfigLoadEnd,
 RoutesRecognized,
 GuardsCheckStart,
 ChildActivationStart,
 ActivationStart,
 GuardsCheckEnd,
 ResolveStart,
 ResolveEnd,
 ActivationEnd
 ChildActivationEnd
 NavigationEnd,
 NavigationCancel,
 NavigationError
 Scroll

Is the Routing Module Mandatory for an


Application?
No, routing module can be totally skipped if there are simple
configurations.

What Is a Wildcard Route?


Wildcard route has the path that consists of two asterisks (**) that can
match any URL. It is helpful when a URL doesn’t match any of the
predefined routes. Instead of throwing error, we can use a wildcard route
and defining a component for the same.

Question: Explain the Lifecycle Hooks


The set of processes that Angular goes through from initiation through end
together are called as lifecycle hooks.

ngOnChanges This method is called when the value of a data-bound property changes

ngOnInit This is called whenever the initialization of the directive/component happens.

ngDoCheck This method is for detecting and taking action on changes that Angular won't detect on
ngAfterContentInit This is called in response after Angular projects any external content into the compon

ngAfterContentChecked This is called in response after Angular checks the content projected into the compone

ngAfterViewInit This is called in response after Angular initializes the component's views and child vie

ngAfterViewChecked This is called in response after Angular checks the component's views and child views.

ngOnDestroy This is the clean-up done before Angular destroys the directive/component.

Question: How Are Animations Done in


Angular?
Answer: To use the animation module, it has to be enabled. For this, the
BrowserAnimationModule has to be imported.
Plain Text

import { BrowserAnimationsModule } from


'@angular/platform-browser/animations'; After this, import the required
animation functions into the component files. Example, import { state,
animate, transition, // ... } from '@angular/animations';

Next, add the animation metadata property within the @Component()


decorator in the component file.
Plain Text
1

@Component({ selector: 'app-root', templateUrl: 'app.component.html',


animations: [ // animation triggers go here ] })

Question: What Are the Special Transition


States?
Answer: Special transition states are wildcard (*) and void. Wildcard
matches any animation state. The void state is used to configure transitions
for elements entering or leaving a page.

Question: How Can You Disable All the


Animations in Angular?
Answer: To disable all the animations, place the @.disabled host binding
on the topmost Angular component.

1. Explain the steps to create a reusable animation.

To create an animation that can be reused, use the animation() method and
define the animation in a separate .ts file. Declare this animation as a const
export variable. This can be then imported and reused in any app
components that use the useAnimation() API. Check an example on
the Angular website.

Question: Mention Some of the Functions


That Help Control Complex Animation
Sequences
Answer:

query() finds one or more inner HTML elements within the current element being animated in the sequenc

stagger() applies a cascading delay (timing gap) after each animation

group() runs multiple animation steps in parallel.

sequence() runs animation steps one after another (sequentially)

Explain the Features of Forms in Angular.


Answer: There are two approaches to handle form data (user inputs) –
reactive and template-driven.
Reactive forms can be used when you are using reactive patterns in your
application and forms are a key part of your application. These forms are
scalable, robust and testable.
Template-driven forms are used to add simple forms, for example, a sign-
up page. These are not as scalable as reactive forms and should be used
only if your form requirements are simple and minimal.

How Is Metadata Represented in Angular?


Answer: Metadata is represented using decorators like class decorators,
property decorators, method decorators, property decorators. Example,
@Component, @NgModule etc…

What Are Class Decorators in Angular?


Answer: Class decorator contains the metadata of the suitable class type. It
appears just before the class definition and declares the class to be of a
certain type. Some class decorators are — @Component, @NgModule,
@Pipe, @Directive, @Injectable.
Explain the Difference Between Annotations
and Decorators in Angular
Answer: Annotations are hardcoded features of Angular and store array in
it. The compiler creates am attribute of the annotated class and instantiates
an object of the same name, passing the metadata to the constructor.
Decorators, on the other hand, are functions that receive the object to be
decorated. After receiving, they are free to modify the object in the way it
likes. Decorators are implemented by the TypeScript compiler.

What Is the Difference Between Class


Decorators and Class Field Decorators?
Answer: Class decorators appear just before class definition, whereas class
field decorators appear just before a field in the class definition. Examples
of class decorators are @Component, @NgModule etc… Examples of a class
field decorator are @Input, @Output etc…

Question: What Is Package.json? Explain its


Purpose
Answer: With json package, it becomes easy to manage the project
dependencies. We can mention details like the version, language etc… in
package.json. For example, if typescript is used in our project, we can
mention typescript and its version in package.json. Examples are
metadata.json, tsconfig.json etc…

Question: What Does {{}} Represent? What Is


It Used For? Show an Example
Answer: The double curly braces represent interpolation. It is a special
syntax. Angular converts it into property binding. You can think of it as an
alternate for property binding. The name of the component is written
inside the inner curly braces. During execution, the name is replaced by the
actual string value of the property. For example,
<h2> {{apptitle}} <img src="{{imgname}}" style="height:30px">
</h2>

Angular will evaluate and replace apptitle and imgname with their actual
values.

Question: What Does the Representation [()]


Mean?
Answer: This is a representation for ngModel used for two-way data
binding. It is written as [(ngModel)] = “propertyvalue”.

What Is a Bootstrapping Module in Angular?


Answer: The root module that you bootstrap to launch the application is
called as a bootstrapping module. Every Angular application has a
bootstrapping module. It is also called as the AppModule. The
bootstrapping module is mentioned in the AppModule class.
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule,
FormsModule, HttpClientModule ], providers: [], bootstrap:
[AppComponent] }) export class AppModule { }

Some Differences Between Promise and


Observable
Answer:

Promise Observable
Executes immediately as soon as created Executes only when the subscription starts

Has chaining and subscription to handle complex


Used with .then() clause
applications

Centralized and predictable error handling by the use of


Errors are pushed to child promises
subscribe() method

Provides only one value Can provide multiple values over time

Question: What Is the Single Page


Application? How Is It Different From
Traditional Web Technology?
Answer: In a single page application (SPA), only the home page
(index.html) is maintained throughout even though the URL keeps on
changing. It is faster and easier to implement when compared with
traditional web technology. In traditional technology, every time a user
makes a request, the request is passed on to the server. This takes more
time.

Question: What Are the Different Types of


Compilations in Angular?
Answer: Two types of compilations – AOT (Ahead-of-Time) and JIT (Just-
in-Time).

List the Differences Between Just-In-Time


(JIT) Compilation and Ahead-Of-Time (AOT)
Compilation
Answer: With JIT, the compilation happens during run-time in the browser.
It is the default way used by Angular. The commands used for JIT
compilation are –
ng build ng serve

In AOT compilation, the compiler compiles the code during the build itself.
The CLI command for aot compilation is -
ng build --aot ng server –aot

AOT is more suitable for the production environment whereas JIT is much
suited for local development.

Which One Is Better out of AOT and JIT?


Answer: AOT reduces the load and bootstrap time of the application. The
pages also load faster. Any errors are also shown during the time of
application build itself. Hence, AOT is a better option.

Discuss Some Differences Between Angular


and Jquery. Which One Is Most Suitable for a
Complex Website With Many Workflows?
Answer:

Angular jQuery

Front end framework based on TypeScript and JS library that supports animation and
JavaScript DOM manipulation

Two-way data binding is possible Two-way data binding cannot be done

Form validation can be done No option for form validation

Supports RESTful apis No support for RESTful apis


For a complex website with multiple workflows, Angular is more suitable
and easier to develop and maintain.

What Is an Angular Library? Can You Create


Your Own Library in Angular?
Answer: Angular library is a set of generic solutions that other developers
have put together to be re-used. We can create own library using Angular.
These libraries can be published and shared as npm packages. A library
should be imported in the app.

What Do You Know About the NPM Package?


Answer: The components, framework and CLI used by Angular
applications are packaged as npm packages. Npm packages can be
downloaded using the npm CLI client.

Question: Write a Sample Code to Create a


Library
Answer: You can use the Angular CLI for this. The following set of
commands generates a new library skeleton –
ng new my-workspace --create-application=false cd my-workspace

ng generate library my-lib

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:


1. Selector - used for accessing the component
2. Template/TemplateURL - contains HTML of the component
3. StylesURL - contains component-specific stylesheets

After this, Angular calls the index.html file. This file consequently calls
the root component that is app-root. The root component is defined
in app.component.ts.
This is how the index.html file looks:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-
scale=1">
</head>
<body>
<app-root></app-root>
</body>
</html>

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

This is how every angular application works.

What is AOT compilation? What are the


advantages of AOT?
Every Angular application consists of components and templates which
the browser cannot understand. Therefore, all the Angular applications
need to be compiled first before running
Inside the browser.
Angular provides two types of compilation:
 JIT(Just-in-Time) compilation

 AOT(Ahead-of-Time) compilation
In JIT compilation, the application compiles inside the browser during
runtime.
Whereas in the AOT compilation, the application compiles during the build
time.

The advantages of using AOT compilation are:

 Since the application compiles before running inside the browser, the browser loads the executable
code and renders the application immediately, which leads to faster rendering.

 In AOT compilation, the compiler sends the external HTML and CSS files along with the application,
eliminating separate AJAX requests for those source files, which leads to fewer ajax requests.

 Developers can detect and handle errors during the building phase, which helps in minimizing
errors.

 The AOT compiler adds HTML and templates into the JS files before they run inside the browser. Due
to this, there are no extra HTML files to be read, which provide better security to the application.

By default, angular builds and serves the application using JIT compiler:

ng build
ng serve

For using AOT compiler following changes should be made:

ng build --aot
ng serve –aot

Modules
A module is a place where we can group components, directives,
services, and pipes. Module decides whether the components, directives,
etc can be used by other modules, by exporting or hiding these elements.
Every module is defined with a @NgModule decorator.
By default, modules are of two types:
 Root Module
 Feature ModuleEvery application can have only one root module whereas,
it can have one or more feature modules.
A root module imports BrowserModule, whereas a feature module
imports CommonModule

How are observables different from promises?


The first difference is that an Observable is lazy whereas a Promise
is eager.
Promise Observable

Emits multiple values over a


Emits a single value
period of time

Lazy. An observable is not


Not Lazy called until we subscribe to
the observable

Can be cancelled by using


Cannot be cancelled
the unsubscribe() method

Observable provides
operators like map, forEach,
filter, reduce, retry,
retryWhen etc.
observables are lazy. Observable runs only when someone subscribes to
them

promise runs before the then method is called. Therefore, promises


are eager

The next difference is that Promises are always asynchronous. Even


when the promise is immediately resolved. Whereas an Observable, can
be both synchronous and asynchronous

The biggest feature of using observables is the use of operators. We can


use multiple operators on an observable whereas, there is no such
feature in a promise.

what is dependency injection in simple terms?


Let’s break it down, dependencies in angular are nothing but services
which have a functionality. Functionality of a service, can be needed by
various components and directives in an application. Angular provides a
smooth mechanism by which we can inject these dependencies in our
components and directives.
So basically, we are just making dependencies which are injectable
across all components of an application.

we can create injectable dependencies by adding


the @Injectable decorator to a class.