Angular
Angular
Angular
Modules
Component
Template
Directives
Data Binding
Services
Dependency Injection
Routing
What is ViewEncapsulation?
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.
What is Redux?
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.
Accessibility Applications
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 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.
Angular offers code completion, instant errors, etc. with popular source code editors and
IDEs.
Templates
Testing
Angular lets you carry out frequent unit tests using Karma. The Protractor allows
running faster scenario tests in a stable way.
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.
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.
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.
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.
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.
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
Root $scope
o $scope for Controller 1
o $scope for Controller 2
o …
o ..
o .
o $scope for Controller n
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
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 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
Attribute Directives
Component Directives
Structural Directives
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:
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?
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.
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”
Interface OnInit {
ngOnInit() : void
function Dummy(target) {
dummy.log('This decorator is Dummy', target);
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.
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:
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,
Expressions are evaluated against a scope object Expressions are evaluated against the global wind
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.
Component 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
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.
limitTo Limits array into the specified number of elements; string to specified number of characters
JS modules NgModules
The second part (i=index) is optional and only needed if you want to
display the index.
Can be shared with many different It cannot be shared because the internal state can be affected
instances by any factors.
NavigationStart,
RouteConfigLoadStart,
RouteConfigLoadEnd,
RoutesRecognized,
GuardsCheckStart,
ChildActivationStart,
ActivationStart,
GuardsCheckEnd,
ResolveStart,
ResolveEnd,
ActivationEnd
ChildActivationEnd
NavigationEnd,
NavigationCancel,
NavigationError
Scroll
ngOnChanges This method is called when the value of a data-bound property changes
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.
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.
query() finds one or more inner HTML elements within the current element being animated in the sequenc
Angular will evaluate and replace apptitle and imgname with their actual
values.
Promise Observable
Executes immediately as soon as created Executes only when the subscription starts
Provides only one value Can provide multiple values over time
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.
Angular jQuery
Front end framework based on TypeScript and JS library that supports animation and
JavaScript DOM manipulation
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:
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular';
}
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.
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.
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
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
Observable provides
operators like map, forEach,
filter, reduce, retry,
retryWhen etc.
observables are lazy. Observable runs only when someone subscribes to
them