0% found this document useful (0 votes)
315 views

ANGULAR 8 Interview Questions

The document provides explanations for Angular interview questions. It contains 20 questions and answers related to Angular components, installing Angular and related tools, file structure, decorators, routing and more. The answers provide concise technical details and code examples.

Uploaded by

king4u9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
315 views

ANGULAR 8 Interview Questions

The document provides explanations for Angular interview questions. It contains 20 questions and answers related to Angular components, installing Angular and related tools, file structure, decorators, routing and more. The answers provide concise technical details and code examples.

Uploaded by

king4u9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 50

============ ANGULAR 8 Interview Question and

Answers ==========

*******************************

===================================================================================
==========================================================================

1) Explain Component in Angular??


------------------------------

A) - Simple Typescript class behaves like Component.

- We can create more than on Component.

- Angular Applications are Component based Applications.

- Because of Components code Reusability is High in Angular.

- We can provide communication between one Component to another Component.

- Angular follows the MVC Architecture.

- Component Acting as Interface between View and Service.

- Typescript classes behaves like Component.

===================================================================================
===========================================================================

2) how to install yarn tool and explain it??


-----------------------------------------

A) - yarn is the tool given by Facebook.

- yarn tool used to download the libraries from Git.

- We will install "yarn" tool by using following command

> npm install -g yarn@latest

- npm stands for Node Packaging Manager

- npm is the integrated tool of NodeJs

- "-g" stands for global installation.

===================================================================================
============================================================================

3) How to install Angular 8 ??


-------------------------

A) - We will install angular8 by using following command

> npm install -g @angular/cli@latest


- cli stands for command line interface

- cli is the tool used to build and execute the angular applications.

===================================================================================
===========================================================================

4) How to link yarn to CLI tool??


==============================

A) - link the yarn tool to CLI tool

> ng config -g cli.packageManager yarn

===================================================================================
============================================================================

5) How to add angular material and Explain it??


-----------------------------------------------------------

A) - "angular material" is the library given by google.

- "angular material" library used to develop the Rich UI.

- "angular material" is recomended for angular applications

- we will add angular material by using following command

> ng add @angular/material

===================================================================================
===========================================================================

6) What is node_modules directory in Angular??


-------------------------------------------

A) - This directory containes libraries.

- These libraries helps to execute the angular applications.

- It is a repository of all packages currently installed for your project.

===================================================================================
==========================================================================

7) what is app.module.ts in angular ??


-------------------------------------
A) - "app.module.ts" file called as configuration file.

- "app.module.ts" file used to register the angular applications.

- once if we register, then only our applications will be executed.

===================================================================================
==========================================================================

8) what is the use of assets folder in angular ??


------------------------------------------------
A) - This directory used to deploy the static resources.

Example:
-------

logos, XML files, json files, fonts, custom fonts ....... and so on.

===================================================================================
===========================================================================

9) what is main.ts in angular ??


------------------------------

A) - angular starts the execution from "main template".

- "index.html" file is the "main template"

- "main template" internally invokes the "main.ts" file.

- "main.ts" file internally invokes the "app.module.ts" file.

- "app.module.ts" file containes our applications registrations.

- based on "app.module.ts" file our applications will be executed by angular


framework.

- "main.ts" file acting as interface between "index.html" and "app.module.ts"


file.

===================================================================================
==========================================================================

10) what is the use of polyfills.ts in angular ??


----------------------------------------------

A) - this file acting as transpiler.

- this file used to convert the TypeScript to Equalent JavaScript.

- in general we will develop angular applications by using TypeScript.

===================================================================================
==========================================================================

11) what is angular.json file in angular ??


----------------------------------------

A) - It is application configuration file that specifies the startup file, global


css and js to use, browser to target, etc.

- It will explain directory structure of angular application.

- It is used to link the external libraries/technologies to angular framework.

Example:
--------
jQuery, ReactJS, d3JS, underscorejs,------and so on.
===================================================================================
============================================================================

12) what is browserslist ??


-------------------------

A) - it will show supporting browers of angular applications.

===================================================================================
============================================================================

13) what is use of package.json file in angular ??


-----------------------------------------------

A) - This file used to download the 3rd party libraries

- It containes instructions to execute angular applications

===================================================================================
=============================================================================

14) what is & Why Decorator's ??


-------------------------

A) - We can use predefined classes by using "@".

- Using predefined classes by using @ symbol called as "decorator".

- Decorators are used to defined the Meta Data.

===================================================================================
==========================================================================

15) Explain Selector ??


-------------------

A) - selector is the json key used to define the custom HTML element.

- It specifies a reference that is used to access the component in any page.

===================================================================================
========================================================================

16) What is templateUrl ??


----------------------

A) - templateUrl is the json key used to link the external template to component

- It specifies the name and path of HTML file that containes the markup for your
component.

===================================================================================
========================================================================

17) what is styleUrls ??


---------------------

A) - It specifies the name and path of style sheet. That contains the styles used
for component.

===================================================================================
===============================================================================

18) Explain Angular Versions ??


------------------------------

A) --> Angular 2 - September 14, 2016

--> Angular 4 - March 23, 2017

--> Angular 5 - November 1, 2017

--> Angular 6 - May 4, 2018

--> Angular 7 - Oct 18, 2018

--> Angular 8 - May 28, 2019

Note ===> - Angular 3 was never initiated and released due to "Routing"
improvements.

- Angular 2 have all library Version 2.

- In Angular 2 routing library improved and released as 3.

- To avoid versions issue in next release angular team ignored 3 and


released the next version as 4.

===================================================================================
=================================================================================

19) What is BrowserModule in Angular ??


-------------------------------------

A) - BrowserModule is the predefined class.

- BrowserModule class used to execute the projects into different browsers.

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

===================================================================================
============================================================================

20) Explain Toastr Notifications ??


---------------------------------

A) - "Toastr Notifications" are "popup" notifications.

- "Toastr Notifications" will display upto few seconds on webpage.

- "Toastr Notifications" are 3rd party Application.

- we will download "Toastr Notifications" by using "yarn" tool

Module : ngx-toastr
> yarn add ngx-toastr --save

- following Git Repository Representing "Toastr Notifications"

URL : https://www.npmjs.com/package/ngx-toastr

Step 1.
download ngx-toastr module
> yarn add ngx-toastr --save

Step 2.
add "ToastrModule" in "app.module.ts"

app.module.ts
-------------
import { ToastrModule } from "ngx-toastr";

imports: [
BrowserModule,
BrowserAnimationsModule,
ToastrModule.forRoot()
]

"forRoot()" function injecting 3rd party module to our native module

Step 3.
copy the styles from Git Repository to "styles.css" file

Step 4.
make the "Toastr Styles" available globally with the help of "angular.json"
file.

angular.json
------------
"styles": [
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.css",
"node_modules/ngx-toastr/toastr.css"
]

===================================================================================
==========================================================================

21) Explain HttpClient ??


--------------------

A) - "HttpClient" is the predefined service.

- "HttpClient" introduced in Angular4.3

- "HttpClient" used to make the Rest API Calls.

- "HttpClient" present in "HttpClientModule".

- "HttpErrorResponse" also predefined service in "HttpClientModule".


- "HttpErrorResponse" used to handle the errors while executing Rest API Calls.

- "HttpClient", "HttpClientModule" and "HttpErrorResponse" present in


@angular/common/http package.

- Receiving the continuous data from server, (when ever updates available) called
as Observable.

- Observable is the predefined class present in "rxjs" package.

- "rxjs" stands for Reactive Extension JavaScript.

- "HttpClient" return type is Observable.

===================================================================================
=============================================================================

22) Explain Unit Test Cases ??


---------------------------

A) - Testing Divided into two types.

1) Manual Testing

2) Automation Testing

- Manual Testing is deprecated now a days all most all the


projects using Automation Testing.

- Automation Testing Testing Divided into 3 Types.

1) Unit Testing

2) Integration Testing

3) End to End(e2e) Testing

- Testing particular functionalites with assumptions called as


"Unit Testing".

- "karma with jasmine" is the tool, used to write the


unit test cases.

- "karma with jasmine" is the inbuilt tool of


Angular Framework.

- we will run "karma with jasmine" tool by using following


command

> ng test

- Testing particular functionality with real scenarios


called as Integration Testing.

- Testing particular functionalities in production environment


called as end to end testing.
- "protractor" is the automation tool used to write the
end to end test cases.

Note : unit test cases file should end with ".spec" extension

===================================================================================
==========================================================================

23) Explain Template Driven Forms ??


===============================

A) - Template Driven Forms mainly on Application Design(View).

- Now a days no one using Template Driven Forms, all most all the projects
using Model Driven Forms.

- Template Driven Forms have less features compared to Model Driven Forms.

- Template Driven Forms present in "FormsModule"

- "FormsModule" present in "@angular/forms" package.

===================================================================================
==========================================================================

24) What is Pipes ??


-----------------

A) - pipes are used to display the data based on customers requirement.

- Pipes are usually used to format and filter the data.

- Technically Pipe is a class derived from pipe transform. It implements the


features of pipe transform.

- we have two types of pipes.

=> predefined pipes


=> custom pipes

===================================================================================
============================================================================

25) What is predefined pipes ??


------------------------------

A) The pipes given by angular framework called as predefined pipes

predefined pipes
----------------
=> uppercase
=> lowercase
=> titlecase
=> date
=> currency
=> json
=> percent
=> number
=> slice
=> async

===================================================================================
==============================================================================

25) what is custom pipes ??


=======================

A) - The pipes developed by us based on application requirement called as custom


pipes

- creating our own pipes based on application requirement called as Custom


Pipe.

- Pipe is the predefined class used to assign the logical name to Custom Pipe.

- transform(-) is the predefined function in angular, used to provide the


custom pipe implementation.

- in general we will register pipes in "declarations" array.

===================================================================================
=================================================================================

26) Explain the Communication Between Components in Angular ??


==========================================================

A) - In Angular, we can create more than one component.

- Angular applications are Component Based Applications.

- Because of Components Code Reusability is high in Angular Compared to


AngularJS.

- In Angular, we can provide Communication Between Components in 4 ways

@Input()
@Output()
@ViewChild()
@ViewChildren()

- @Input() Decorator used to share the data from Parent Component to Child
Component.

- @Output() Decorator used to share the data from Child Component to Parent
Component.

- "@ViewChild()" & "@ViewChildren()" are used to share the data between


independent Components.

===================================================================================
================================================================================

27) Explain Services in Angular ??


================================

A) - A Service is a predefined Business Logic which you can reuse in any component.
- Services are used to share the common business logic to multiple components.

- We have 2 types of sevices

1) predefined services

2) custom services

- services provided by Angular Framework called as predefined services.

- HttpClient is the predefined service, used to make the Rest API Calls.

- "BehaviourSubject" is the predefined service, used to sync the Data between


components.

- The services developed by us based on application requirement called as custom


services.

- "Injectable" is the predefined class used to create the custom services.

===================================================================================
=================================================================================

28) WHAT IS THE DIFFERENCE BETWEEN ANGULAR 2, 4, 6, 8 ??


======================================================

A) Angular 2:
==========

1) Angular 2 is the rewrite and copied version of the basic angular framework

2) This framework is built around the concept and logic circle of components

3) Angular 2 is not incorporated with the feature of backward compatibility which


implies that angular 2 application can not run on angular is the platform.

4) It supports service/controller architecture

5) Angular 2 uses ES2, ES6 typescript

Angular 4:
===========

1) Angular 4 is the rewrite version of angular 2 but is it added with the feature
of backward compatibility

2) This framework is added with the feature of supporting typescript

3) Angular 4 is backward compatible with the Angular 2 framework for most of the
applications.

4) Its support module /component and templates-based architecture

5) Angular 4 uses 2.4 typescript

Angular 6:
==========
1) Angular 6 is the advanced version of Angular 4 which is faster and easy to use
the framework.

2) Angular 6 enables the users to make an angular component and distribute it as a


web component.

3) This framework is compatible with all the previous versions of angular.

4) It supports angular-plugin architecture

5) The typescript ES6 and 2.4 are used by this framework of angular.

Angular 8
=========

1) Angular 8 is the latest version of the angular framework which is incorporated


with differential loading of modern JavaScript feature

2) This framework enables users to create their own components as per their
usability criteria.

3) This version of Angular is fully compatible with all the existing versions of
angular.

4) The architecture which supports all the latest and previous feature of angular
are supported by this framework.

5) The typescript 3.4 is supported by the latest version of angular

===================================================================================
===============================================================================

29) What are the new features in angular 8 ??


==========================================

A) Angular 8 it has following new features such as


------------------------------------------------

Differential loading:
======================

It is a technique which automatically makes your angular applications more


performant. When you build applications for production, two bundles are created-
One
bundle for Modern browsers that support ES6+ and another bundle for older
browsers that only support ES5.

Dynamic imports for lazy routes:


===============================

In Angular version 8 there is nothing new in the concept of lazy routes itself
but the syntax has totally changed. In the older version of Angular CustomString

Syntax is used, but angular 8 uses standard dynamic import syntax so the syntax
which is customized to Angular is migrated to industrial standard.

Ivy rendering Engine:


=====================
It translates the templates and components into regular HTML and javascript that
the browser can interpret and understand.

Bazel:
======

It is a building tool through which angular developer can build backends and
frontends.

===================================================================================
============================================================================

30) What is runGuardsAndResolvers in Angular 8 ??


==============================================

A) - Angular 8 introduced a number of new and unique options to


"runGuardsAndResolvers."

- In general, "runGuardsAndResolvers" is an option which is used for the Angular


router configuration in order to control the resolvers and guards.

- The first option available in "runGuardsAndResolvers" is pathParamsChange.


Through, this option router will re-run the guards and resolvers.

- Whenever you want to control over the resolvers and guards, use
runGuardsAndResolvers option in Angular 8.

===================================================================================
=============================================================================

31) What is typeofchecks in Angular 8 ??


=====================================

A) - The working of typesofchecks in Angular 8 is similar with the enabled and


disabled flag, which means if you want to test whether the selected value is an
object
or not, then the following syntax is used " Typeof value = = = 'object' ".

- In angular 8 the folwing types of checks are used such as “Typeof


value.ngOnDestroy = = = 'function' “.

===================================================================================
=================================================================================

32) What are the advantages of using Angular ??


=============================================

A) A few of the major advantages of using Angular framework are listed below:
----------------------------------------------------------------------------

- It supports two-way data-binding

- It follows MVC pattern architecture

- It supports static template and Angular template

- You can add a custom directive


- It also supports RESTfull services

- Validations are supported

- Client and server communication is facilitated

- Support for dependency injection

- Has strong features like Event Handlers, Animation, etc.

===================================================================================
==========================================================================

33) What is the difference between ng-template, ng-container, and ng-content in


Angular ??

===================================================================================
===

A) ng-template :
=============

- Used to create partial HTML template which needs to be reused.

Note: syntax of using Structural Directives on ng-template is different because in


the compilation process angular converts structural directives into the ng-template

tags.

That's why two templates will not work. So we have different tricks to use them.

use of *ngIf:

<ng-template [ngIf]="newuser">

Welcome to Angular !

</ng-template>

use of *ngFor:

<ng-template ngFor let-emp [ngForOf]="employeeList">

ng-container:
============

- Used when there are use of more that two structural directives.

- Used when have to call a ng-template with the help of its *ngTemplateOutlet
attribute.

- Used when don't need a DOM tag at run-time, but need to use an angular
Structural Directive.

<ng-container *ngTemplateOutlet="demotemplate"></ng-container>
<ng-template #demotemplate>
Welcome to DritalConnect!
</ng-template>

ng-content:
===========

- Used when need to keep the component's HTML content dynamic, so that anyone
can add their own content inside the Component as per their requirement.

- This tag defines the place where in the Component the coming HTML will be
placed.

Component html:
===============

(Let's suppose we have created a component IQComponent with selector <angular-


questions>)

<h1>Angular Interview Questions</h1>

<ng-content></ng-content>

<p>All the Best!!</p>

Now how to call this component in HTML:


=======================================

(The content inside the selector tags will be rendered in place of the <ng-
content> in the above component HTML)

<angular-questions>

<p> Part 1 </p>

<h1>Q1. What is angular?</h1>

<h1>Q2. Why to use angular?</h1>

</angular-questions>

Another call of same component with different content:


======================================================

<angular-questions>

<p> Part 2 </p>

<h1>Q16. What is directive?</h1>

<h1>Q17. Why are pipes?</h1>

</angular-questions>
===================================================================================
============================================================================

34) Why learn Angular ??


====================

A) - Angular is a Javascript Framework that is used by developers for building web,


desktop, and mobile applications.

- Development of Angular Applications involves usage of Typescript, which is a


superset of Javascript, along with HTML, CSS etc..

- The code written in Typescript compiles to Javascript and is rendered in the


browser.

- Angular is one of the most popular Javascript Frameworks for building web
applications.

5 Reasons to Learn Angular:


===========================

1) Angular supports Single Page Applications.

2) Two-way data binding.

3) Cross-Platform

4) Reduced Coding

5) Modularity in Angular

Versions of Angular
===================

AngularJS ( also known as Angular 1 )

Angular 2

Angular 4

Angular 5

Angular 6

Angular 7

Angular 8

Angular 9

Popular websites developed using Angular


========================================

1) Paypal

2) Upwork
3) Netflix

4) Freelancer

===================================================================================
================================================================================

35) Why You Use Browsermodule, Commonmodule, Formsmodule, Routermodule, And


Httpclientmodule ??

===================================================================================
==========

A) BrowserModule :
---------------

The browser module is imported from @angular/platform-browser and it is used


when you want to run your application in a browser.

CommonModule :
-------------

The common module is imported from @angular/common and it is used when you want
to use directives - NgIf, NgFor and so on.

FormsModule :
-------------

The forms module is imported from @angular/forms and it is used when you build
template driven forms.

RouterModule :
---------------

The router module is imported from @angular/router and is used for routing
RouterLink, forRoot, and forChild.

HttpClientModule:
-----------------

- The HttpClientModule is imported from @angular/common/http and it used to


initiate HTTP request and responses in angular apps.

- The HttpClient is more modern and easy to use the alternative of HTTP.

===================================================================================
============================================================================

36) What Is Parameterizing Pipe ??


==============================

A) - A pipe can accept any number of optional parameters to achieve output.

- The parameter value can be any valid template expressions.

- To add optional parameters follow the pipe name with a colon (:).
- Its looks like- currency: 'INR'

In the following example –


------------------------

<h2>The birthday is - {{ birthday | date:"MM/dd/yy" }} </h2>

<!-- Output - The birthday is - 10/10/1989 -->

===================================================================================
=============================================================================

37) What Is A Cookie ??


=====================

A) A cookie is a small piece of data sent from a website and stored on the user's
machine by the user's web browsers while the user is browsing.

===================================================================================
==============================================================================

38) Explain the difference between "Constructor" and "ngOnInit" ??


==============================================================

A) -> The Constructor is a default method of the class that is executed when the
class is instantiated and ensures proper initialization of fields in the class and
its

subclasses.

-> ngOnInit is a life cycle hook called by Angular to indicate that Angular is
done creating the component. We have to import OnInit in order to use like this

(actually implementing OnInit is not mandatory but considered good practice).

-> Mostly we use ngOnInit for all the initialization/declaration and avoid stuff
to work in the constructor.

-> The constructor should only be used to initialize class members but shouldn't
do actual "work".

===================================================================================
===============================================================================

38) What is one way data Binding ??


=============================

A) - In one-way Binding the model data is updated to the view but any change in the
View will not update the Model.

- It is a read only technique often called as "interpolation".

- The model data is Binded to view by using databinding "{{}}" expression.

Note:
=====

Interpolation will not use any property Binding. It Binds value to any attribute
directly by using "{{}}" databinding expression.

===================================================================================
=================================================================================

39) What is Two-way data binding ??


===============================

A) - The two-way data binding technique allows the changes in View to update in
the Model.

- It uses a combination of property "[]" and event "()" binding.

- The directive "ngModel" is responsible for handling the property and event
binding for any specific element.

- ngModel is defined in "formsModule" of "angular/forms" library.

syntax:
=======

[(ngModel)] = "property"

- property is a reference where data is updated.

===================================================================================
=================================================================================

40) What is Angular Form validations ??


===================================

A) - Validation is the process of verifying User Input.

- Validation is required to ensure that contradictionary and unauthorized data


is not get stored into database.

- Angular provides built in validation services that are categorized into Twi
types

A) Form state validation services

b) Input state validation services

===================================================================================
===============================================================================

41) What is the difference between an Annotation and a Decorator in Angular ??


==========================================================================

A) -> Decorators are actually the functions, which extends the class object
behavior at design time, by annoting them.

-> But the decorators are imported as a annotation from '@angular/core' and
attached with the class using the sign @.

Example:
=========
@Pipe

class TestPipe { }

-> Here @Pipe is an annotation that tells the Angular, that the class with which
the annotation is attached to will get the Pipe behavior.

===================================================================================
=================================================================================

42) What is Transpiling in Angular ??


=================================

A) - Transpiling means compilation of one High Level Language into another High
Level Language.

- So In Angular, we use TypeScript ( A subset of JavaScript) which is a High


Level Language, so as to maintain OOPS concept.

- But our browser understands only the JavaScript, which again a High Level
Language.

- So we have to transpile the TypeScript to JavaScript (one High Level Language


into another High Level Language), that's what the transpiling in Angular.

===================================================================================
================================================================================

43) How to communicate between the parent and child component in angular ??
=========================================================================

A) Using @Input / @Output:


------------------------

- @Input is defined in child component to receive the value from parent component.

- @Output is defined in child component to emit the data or event from child
component, which parent component receives.

Using @ViewChild / @ContentChild:


--------------------------------

- @ViewChild is used to get the instance of the child component and then can
access any properties of that child component.

- @ContentChild is used to get the instance of the content within the child
component and then can access any properties of that component.

===================================================================================
===============================================================================

44) What is the use of base href in angular ??


===========================================

A) - Base href is used in angular to set the base portion or the static portion of
URL.

- After that part of URL, the angular router considers for the routing path.

- When we define Router Module in any angular application, we have to tell it


that the whats your static part of URL, so that it can start considering for their
router path.

<base href="/">

- Its to be placed in the index.html head tag (main HTML file for angular
application)

===================================================================================
=================================================================================

45) How to define Singleton services in angular ??


==============================================

A) - Singleton services are the services which are only initialized once in a
application.

- Only one instance is created in the whole application.

- Means only one time memory is given, and it retains the same memory for the
entire application.

- It is used to share data from one components to another.

It can be defined by two ways:


==============================

Declare service as root :


-------------------------

- Decorator @Injectable() has providedIn property, which is set to 'root'.

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

@Injectable({
providedIn: 'root',
})
export class DemoService {
}

Include service in MainModule:


-------------------------------
Include the service in the MainModule or in a module that is only imported by
the MainModule.

===================================================================================
=================================================================================

46) What is a declarable in angular ??


==================================

A) - Declarables are the classes that are need to be declared inside the
declarations array in the NgModule.

--> There are three only classes that are declarable in angular:

components

directives

pipes

===================================================================================
============================================================================

47) What is the difference between BrowserModule or CommonModule ??


===============================================================

A) BrowserModule:
=============

- It should be imported only once in a application in the MainModule's imports


array.

- It provides the essential services required to launch and run a browser


application.

- Do not import BrowserModule in any others module.

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

CommonModule:
=============

- It can be imported in any Feature modules and lazy-loaded modules.

- Its is used to get access of Angular providers like *ngIf,*ngFor.

- import {CommonModule} from @angular/common

===================================================================================
===============================================================================
48) What is the use of forRoot() method in angular ??
===================================================

A) - forRoot() is a static method given in Module class, to set its singleton


behavior in the root of Application.

- forRoot() and forChild() are static methods that configure services in the
root and feature modules respectively.

===================================================================================
===================================================================================

49) What if the two modules provide the same service ??


======================================================

A) If the two modules have same services provided, and it gets loaded at the same
time, the last loaded modules's provided service gets the instance of the service
and both the modules uses the same service instance.

===================================================================================
===================================================================================
=

50) What are the types of modules available in angular ??


=====================================================

A) In Angular we have two types of modules:

Shared Module:
==============

- Shared modules have to re-export the components, directives, and pipes.

- Shared Module doesn't re-export providers.

- It is created to share the common business logic, reusable components, pipes


within multiple Modules in the application.

Featured Module:
================

- Featured module are the normal modules, which can't be shared.

- It contains a particular feature, such as routes, services, widgets, etc.

===================================================================================
=================================================================================

51) What is HttpClient in angular ??


=================================

A) ==> HttpClient is the angular inbuilt service used to handle HTTP request in
angular.

==> HttpClient is avaliavle by importing HttpClientModule.


==> import { HttpClientModule } from '@angular/common/http';

==> HttpClient offers a simplified client HTTP API for Angular applications that
rests on the XMLHttpRequest interface exposed by the browsers.

===================================================================================
===================================================================================
=

52) What is difference between HTTP and HttpClient in angular ??


===============================================================

A) --> Http are introduced at the staring of angular to handle HTTP request
response.

---> HttpClient was later introduced in angular 4.3

--> HttpClient is an improved replacement for Http.

--> import { HttpClientModule } from '@angular/common/http';

--> import { HttpModule } from '@angular/http';

===================================================================================
=================================================================================

53) What are the Entry Components in angular ??


============================================

A) Entry Components are the components declared, to tell angular to use it as its
default component which to be render on the index.html at first load.

Entry Components are of two kinds:

At bootstrap in main module:


=============================

We declare a entry component in the bootstrap array in NgModule of appplication


level module (root module).

At route:
=========

We declare a component in a route definition.

===================================================================================
=================================================================================

54) What are the available metadata of NgModule in angular ??


========================================================
A) Eight metadata are available in NgModule:
-----------------------------------------

providers

declarations

imports

exports

entryComponents

bootstrap

schemas

id

@NgModule({

providers?: Provider[]

declarations?: Array<Type<any> | any[]>

imports?: Array<Type<any> | ModuleWithProviders | any[]>

exports?: Array<Type<any> | any[]>

entryComponents?: Array<Type<any> | any[]>

bootstrap?: Array<Type<any> | any[]>

schemas?: Array<SchemaMetadata | any[]>

id?: string

})

===================================================================================
=================================================================================

55) What is AsyncPipe in angular ??


================================

A) --> AsyncPipe is a special kind of impure pipe which makes rendering data from
observable and promises much easier.

--> For promises it automatically adds a then callback and renders the
response.

--> The async pipe subscribes to the given Observable or Promise and returns
the latest value it has emitted in response.

--> When the value is emitted it marks the component to be checked for the
further changes.
--> When the component is destroyed it gets unsubscribes automatically to avoid
the potential memory leakage.

===================================================================================
===================================================================================

56) What is RouterLinkActive in routing in angular ??


=================================================

A) ==> RouterLinkActive is a directive in angular, used to add css to the active


routing link.

==> RouterLinkActive takes css, which it sets to the link, which is currently
active.

Adding single class:


====================

<a routerLink="/category/mobile" routerLinkActive="css-active">Mobile</a>

Adding multiple class:


======================

<a routerLink="/category/mobile" routerLinkActive="css-active font-


large">Mobile</a>

<a routerLink="/category/mobile" [routerLinkActive]="['css-active' , 'font-


large']">Mobile</a>

Adding class if exact match:


===========================

<a routerLink="/category/mobile" routerLinkActive="css-active"


[routerLinkActiveOptions]="{exact:true}">Mobile</a>

Add on parent element:


======================

<div routerLinkActive="css-active" [routerLinkActiveOptions]="{exact: true}">

<a routerLink="/category/mobile">Mobile</a>

<a routerLink="/category/tablet">Tablet</a>

</div>

Add RouterLinkActive instance to a template:


============================================

<a routerLink="/category/mobile" routerLinkActive #catLink="routerLinkActive">

Mobile Link is {{ catLink.isActive ? 'Active Now' : 'Not Active Now'}}


</a>

===================================================================================
=================================================================================

57) What is RouterState in angular ??


==================================

A) RouterState is a interface in angular, which keeps the tree of the activated


routes.

Example to use :
================

@Component({templateUrl:'dritalconnect.html'})

class MyComponent {

constructor(router: Router) {

const routerState: RouterState = router.routerState;

const root: ActivatedRoute = routerState.root;

const child = root.firstChild;

const id: Observable<string> = child.params.map(p => p.id);

}
}

===================================================================================
===================================================================================

58) What are router events in angular ??


=====================================

A) ==> While navigating to the another route, angular router emits some events as
hooks.

==> These events are provides so as to handle, start,end, error etc. during
navigation session.

Available list of events are as follows:


========================================

NavigationStart

RouteConfigLoadStart

RouteConfigLoadEnd

RoutesRecognized

GuardsCheckStart

ChildActivationStart
ActivationStart

GuardsCheckEnd

ResolveStart

ResolveEnd

ChildActivationEnd

ActivationEnd

NavigationEnd

NavigationCancel

NavigationError

Scroll

===================================================================================
===================================================================================

59) What is ActivatedRoute in routing in angular ??


===============================================

A) Its a interface available in '@angular/router' which contains the information


about the current active route.

It have following properties:


===============================

interface ActivatedRoute {

snapshot: ActivatedRouteSnapshot

url: Observable<UrlSegment[]>

params: Observable<Params>

queryParams: Observable<Params>

fragment: Observable<string>

data: Observable<Data>

outlet: string

component: Type<any> | string | null

routeConfig: Route | null

root: ActivatedRoute

parent: ActivatedRoute | null

firstChild: ActivatedRoute | null


children: ActivatedRoute[]

pathFromRoot: ActivatedRoute[]

paramMap: Observable<ParamMap>

queryParamMap: Observable<ParamMap>

toString(): string

===================================================================================
================================================================================

60) What is meant by wildcard route in angular ??


=============================================

A) --> It's the else like condition defined in the route, if URL does not matches
any of the defined routes, it considers the wild card route.

--> Wild card route is defined with double asterisk. (**)

--> Wild card route is kept at the last of the of the routes array.

--> Wild card route should be only one in the whole application.

{ path: '**', component: PageNotFoundComponent }

===================================================================================
=================================================================================

61) What is the purpose of Wildcard route ??


========================================

A) - This is useful for displaying a "404 - Page Not Found".

- Or to redirecting to another route, like to the home page.

- Its like a else condition in if/else, to catch if route is not found.

===================================================================================
=============================================================================

62) How to set redirects in router ??


=================================

A) { path: 'mobile', redirectTo: '/electronics', pathMatch: 'full' },

{ path: 'tablet', redirectTo: '/electronics', pathMatch: 'full' },

===================================================================================
============================================================================
63) How to navigate to another routing in typescript ??
===================================================

A) this.router.navigate(['/another-path']);

===================================================================================
============================================================================

64) What is guard in angular ??


===========================

A) Guard in angular is used to allow to grant or remove access to the certain


routes.

There are 4 types of guard, which are defined in the route.

1. CanActivate :
------------------

CanActivate used to give the permission to enter into main routes.

2. CanDeacticate :
------------------

CanDeactivate used to give the permission to leave main routes.

3. CanLoad :
------------

It checks whether user have access to navigate to the given path or not,
especially used for the lazy loading Featured modules. It even stops from loading
of the

module, if the guard responses false.

4. CanActivateChild :
--------------------

CanActivateChild used to give the permission to enter into child routes.

===================================================================================
=================================================================================

65) What is Parameter routing ??


===========================

A) When we need to pass the constraint data from the router, we need to define
in the route.

In Routing:
===========

{ path: 'mobile/:id', component:MobileComponent },


In HTML:
========

<a [routerLink]="['/mobile', mobile.id]">Samsung</a>

In Component to receive Id from active route:


============================================

export class DemoComponent implements OnInit {


mobileId: number;

constructor(
private route: ActivatedRoute
) {}

ngOnInit() {
this.route.paramMap.pipe(
switchMap(params => {
this.mobileId = params.get('id');
})
);
}
}

===================================================================================
================================================================================

66) Which module is available in angular for routing ??


===================================================

A) RouterModule

import {RouterModule} from '@angular/router';

===================================================================================
=============================================================================

67) What is the use of forRoort() and forChild() in routerModule ??


===============================================================

A) - forRoort is used to set router config to the root level, in the main module.

- forChild is used to set route config to the child level, in the lazy loading
Featured Modules.

===================================================================================
==============================================================================

68) Can we define more than one RouterOutlet in same component ??


=============================================================

A) Yes, we can.

- For that we have to use auxiliary routing, in which each router outlets
given a unique name.
- At the time of router Link binding , we have to define the name of the
outlet to which have to render the route component.

===================================================================================
=============================================================================

69) What is RouterStateSnapshot in routing in angular ??


====================================================

A) - RouterStateSnapshot represents the state of the router at a moment in time.

- Its a interface having 'url' property.

===================================================================================
============================================================================

70) How to get data from router in angular ??


=========================================

A) Using ActivatedRoute:
======================

We can access the route's data property from the snapshot:

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


import { ActivatedRoute } from '@angular/router';

@Component({
templateUrl: './demo.component.html'
})
export class DemoComponent implements OnInit {
public pageTitle: string;

constructor( private route: ActivatedRoute) {


}

ngOnInit(): void {
this.pageTitle = this.route.snapshot.data['title'];
}
}

===================================================================================
=================================================================================

71) What is JIT ??


==============

A) - Just-in-Time (JIT) is a type of compilation that compiles your app in the


browser at runtime.

- JIT compilation is the default when you run the ng build (build only) or ng
serve (build and serve locally) CLI commands. i.e, the below commands used for JIT

compilation,

ng build

ng serve
===================================================================================
=============================================================================

72) What is the purpose of common module ??


=======================================

A) The commonly-needed services, pipes, and directives provided by @angular/common


module. Apart from these HttpClientModule is available under @angular/common/http.

===================================================================================
===================================================================================

73) What is Angular Ivy ??


==========================

A) Angular Ivy is a new rendering engine for Angular. You can choose to opt in a
preview version of Ivy from Angular version 8.

1) You can enable ivy in a new project by using the --enable-ivy flag with the
ng new command

ng new ivy-demo-app --enable-ivy

2) You can add it to an existing project by adding enableIvy option in the


angularCompilerOptions in your project's tsconfig.app.json.

"compilerOptions": { ... },

"angularCompilerOptions": {

"enableIvy": true

===================================================================================
===================================================================================

74) What are the features included in ivy preview ??


===============================================

A) You can expect below features with Ivy preview,

A) Generated code that is easier to read and debug at runtime

B) Faster re-build time

C) Improved payload size

D) Improved template type checking

===================================================================================
================================================================================

75) What are the class decorators in Angular ??


===========================================

A) A class decorator is a decorator that appears immediately before a class


definition, which declares the class to be of the given type, and provides metadata

suitable to the type The following list of decorators comes under class
decorators,

@Component()

@Directive()

@Pipe()

@Injectable()

@NgModule()

===================================================================================
==============================================================================

76) What is Single Page Applications in Angular ??


-----------------------------------------------

A) - loading one template to another template without refreshing the whole


webpage called as single page application.

- loading one template to another template in single page application called


as Routing.

- "Routes" is the predefined class used to implement the Routing in single


page applications

- "RouterModule" is the predefined module, used to load the Routes into


framework.

- "Router" is the predefined class used to navigate from one template to


another template in single page application.

- "Routes", "RouterModule" and "Router" available in "@angular/router"


package.

===================================================================================
==============================================================================

77) what is lazy loading in angular ??


===================================

A) - loading modules based on application requirement called as Lazy Loading.

- Lazy Loading will improves the application performance.

Advantages of lazy loading:


============================

- High performance in bootstrap time on initial load.


- Modules are grouped according to their functionality.

- Smaller code bundles to download on initial load.

- Activate/download a code module by navigating to a route.

===================================================================================
====================================================================

78) what is HttpRequest, HttpHandler and HttpEvent ??


====================================================

A) - HttpRequest used to take the request from service.

- HttpHandler used to bypass the request to server

- HttpEvent used to handle the exceptions raised by Interceptor.

import { HttpRequest,

HttpHandler,

HttpEvent } from "@angular/common/http";

===================================================================================
===========================================================================

79) Explain interceptors ??


======================

A) - Interceptors acting as client side filters.

- Interceptors authenticate the Http Requests.

- If request is authenticated, then only it will bypass to servers.

- Filters at server side technically called as "middleware".

- server side "middlewares" authenticate the requests before processing the


Http Requests.

Example:
=========

interacting with the databases

===================================================================================
================================================================================

80) what is series & parallel calls ??


===================================

A) - Executing service calls (Rest API calls) with dependencies between them
called as series calls.

- Executing service calls (Rest API calls) without dependencies between them
called as parallel calls
===================================================================================
================================================================================

81) What is forkJoin() ??


=====================

A) - Used to make the parallel Calls in forkJoin() function.

- Accepts an Array of ObservableInput or a dictionary Object of ObservableInput


and returns an Observable that emits either an array of values in the exact same
order as the passed array, or a dictionary of values in the same shape as the
passed dictionary.

forkJoin(...sources: any[]): Observable<any>

- forkJoin is an operator that takes any number of input observables which can be
passed either as an array or a dictionary of input observables. If no input

observables are provided, resulting stream will complete immediately.

- forkJoin will wait for all passed observables to complete and then it will emit
an array or an object with last values from corresponding observables.

===================================================================================
===============================================================================

82) How can I select an element in a component template?


===================================================

A) You can get a handle to the DOM element via ElementRef by injecting it into your
component's constructor:

constructor(myElement: ElementRef) { ... }

===================================================================================
==============================================================================

83) What is an observer ??


======================

A) Observer is an interface for a consumer of push-based notifications delivered


by an Observable. It has below structure,

interface Observer<T> {

closed?: boolean;

next: (value: T) => void;

error: (err: any) => void;

complete: () => void;

}
A handler that implements the Observer interface for receiving observable
notifications will be passed as a parameter for observable as below,

myObservable.subscribe(myObserver);

Note: If you don't supply a handler for a notification type, the observer
ignores notifications of that type.

===================================================================================
================================================================================

84) What is an observable ??


=======================

A) - An Observable is a unique Object similar to a Promise that can help manage


async code.

- Observables are not part of the JavaScript language so we need to rely on a


popular Observable library called RxJS.

- The observables are created using new keyword.

Ex:
---

import { Observable } from 'rxjs';

const observable = new Observable(observer => {

setTimeout(() => {

observer.next('Hello from a Observable!');

}, 2000);

});`

===================================================================================
===============================================================================

85) What are the ways to control AOT compilation ??


================================================

A) You can control your app compilation in two ways

- By providing template compiler options in the tsconfig.json file

- By configuring Angular metadata with decorators

===================================================================================
============================================================================

86) What is router outlet ??


========================

A) The RouterOutlet is a directive from the router library and it acts as a


placeholder that marks the spot in the template where the router should display the

components for that outlet. Router outlet is used as a component,

<router-outlet></router-outlet>

<!-- Routed components go here -->

===================================================================================
===========================================================================

87) What are the utility functions provided by RxJS ??


===================================================

A) The RxJS library also provides below utility functions for creating and
working with observables.

- Converting existing code for async operations into observables

- Iterating through the values in a stream

- Mapping values to different types

- Filtering streams

- Composing multiple streams

===================================================================================
=======================================================================

88) What are Angular expressions ??


===============================

A) Angular expressions are code snippets that are usually placed in binding such
as {{ expression }} similar to JavaScript.

These expressions are used to bind application data to HTML

Syntax: {{ expression }}

===================================================================================
============================================================================

89) List at down the ways in which you can communicate between applications modules
using core Angular functionality ?

===================================================================================
===============================

A) Below are the most general ways for communicating between application modules
using core Angular functionality :
Using events

Using services

By assigning models on $rootScope

Directly between controllers [$parent, $$childHead, $$nextSibling, etc.]

Directly between controllers [ControllerAs, or other forms of inheritance]

===================================================================================
==============================================================================

90) What is the difference between $scope and scope in Angular ??


=============================================================

A) - $scope in Angular is used for implementing the concept of dependency


injection (D.I) on the other hand scope is used for directive linking.

- $scope is the service provided by $scopeProviderwhich can be injected into


controllers, directives or other services whereas Scope can be anything such as a
function parameter name, etc.

===================================================================================
==============================================================================

91) What is Angular Event binding ??


================================

A) - Event is a message sent by sender to its subscriber in order to notify the


change.

- It uses a communication pattern called "observer".

- Observer is a behavioral pattern which provides a way for notifying the


changes to its base class.

- Angular uses all Javascript browser Events, which are categorized into

a) Key Events

b) Mouse Events

c) Miscellaneous Events

- The Events are binded to any element by using "()".

syntax:
======

<button (click)="f1()">

<select (change)="f1()">

- Every browser event comprises of a set of properties that are accesed and
used any function by using the argument $event.

===================================================================================
===============================================================================

92) what is Style Binding ??


========================

A) - Angular supports Binding of inline styles for any specific element.

- The Inline style contains a set of attributes with dynamic values.

- The style object is binded to any element by using the Directive [ngStyle].

Syntax:
-------

.ts
====

public colorName = 'red';

public ApplyColor(){

let obj = {

'color' : this.colorName

return obj;
}

.html
=====

<h2 [ngStyle] = "ApplyColor()"> Text </h2>

===================================================================================
==================================================================================

93) What is change Event Binding ??


===============================

A) - The change Event specifies actions to perform when a value is changed in any
element.

- It is mostly used with in input element like Select, Number, Range, Checkbox,
and Radios.

===================================================================================
================================================================================

94) What is mouse Event Binding ??


===============================

A) - Angular can use the browser mouse events that are used to handle various
interaction with ragard to mouse functionality.

- The commonly used mouse events are...


mousemove
=========

specifies actions to perform while mouse pointer is moving over any element.

mouseover
=========

Actions when mouse pointer is over any element.

mouseout
========

Actions when mouse pointer leaves any element.

mousedown
=========

Actions when mouse left button is down over element.

mouseup
=======

Actions when mouse button released over element.

===================================================================================
===================================================================================

95) What is Key Event Binding ??


============================

A) - Angular supports Binding of Key Events with HTML Elements in order to handle
functionality while user is keying in the characters.

- The key events can also identify the keys and these codes by using following
properties.

keyCode

charCode

which

shiftKey

altKey

ctrlKey

- The commonly is used key events are....

keyup

keydown

keypress

===================================================================================
==============================================================================
96) What is Nested Components ??
============================

A) - A component in angular can use any another component within the content.

- Components can form a Nested hierarchy.

- The Components are accessed within another component by using "selector".

- The properties of one component are not directly accessible in another


component we have to mark them by using @Input() directive, which is derived from
"Input"

of "angular/core" library.

Example:
=======

1. Add following components

> ng g c parent --spec=false

> ng g c child --spec=false

2. Go to child.component.ts

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

export class ChildComponent {

@Input() public uname = 'no_name';

3. Go to child.component.html

<h2 class = "bg-white">

Child Component - Hello ! {{ uname }}

</h2>

4. Go to parent.component.ts

export class ParentComponent {

public userName = 'Ramanababu';

5. Go to parent.component.html

<div class = "container bg-warning">

<h2> Parent Component </h2>

<app-child [uname] = "userName">


</app-child> </div>

===================================================================================
==============================================================================

97) What is Component life cycle in angular ??


===========================================

A) Life Cycle of a component :

Creating a component

Rendering a component

Creating and rendering its child components

Checking data-bound properties

Destroying and removing it from DOM

===================================================================================
================================================================================

98) What is custom events ??


========================

A) - Event is a message sent by sender to its subscriber in order to notify the


change.

- Technically Event is a function that Emits string type value.

- Angular provides EventEmitter base class that have set of properties and
methods for creating a custom event.

- The EventEmitter Emits the value whenever the function is called.

- Angular can use Custom Events for its components, which are defined by using
EventEmitter.

Syntax:
======

public myEvent : EventEmitter<string> = new EventEmitter<string>();

public onMyEvent() {

this.myEvent.emit(stringValue);

<app-yourComponent (myEvent) = "onMyEvent()">

</app-yourComponent>

Note:
=====
The members of a component the Emit value must be designated with "@Output()"
directive in order to use in any another component.

===================================================================================
==================================================================================

99) What Are The Differences Between React And Angular (Simplified) ??
===================================================================

A) The most popular and widely used web application frameworks are REACT and
ANGULAR. We are going to see the differences between those briefly.

React:
======

* ReactJS is an open-source JavaScript Library.

* It was developed and maintained by Facebook.

* It is based on JavaScript and JSX(which is JavaScript example that


looks similar to HTML and CSS, but it uses components and elements of web-like
<div>,<span>, etc).

* It is mostly used to develop single-page applications.

* It is of one-way data binding i.e the data to be passed in only one way
to other parts of application. State is passed to the view and next to other child
components.

* When it comes to understanding and learning react it is comparatively


easy.

* Companies like Facebook, Instagram, Netflix, Airbnb uses react.

* React Native is used to build native mobile apps with existing React
knowledge.

Pros:
=====

* Better user interfaces and easy to launch.

* Faster development and time-saving.

* Easy to integrate third-party libraries.

* One-directional data binding with code stability.

Cons:
=====

* Developers should have great knowledge in integrating with MVC


framework.

* Needs complex configuration and set-up when integrating with MVC


framework.
Angular:
========

* Angular is a full-fledged MVC (Model View Controller) written in


JavaScript.

* It was developed by Google.

* Unlike React, it uses TypeScript (JavaScript-like language) to develop


applications.

* It is majorly used to develop large scale and complex applications.

* It is of 2-way data binding.

* The learning curve is difficult for beginners but difficulty reduces


gradually.

* Companies like Sony, Forbes, Google, Nike uses Angular.

* NativeScript is used to build native mobile apps with existing Angular


knowledge.

Pros:
=====

* It offers high performance of application.

* Code is cleaner and structured.

* It takes everything about routing

* Material design like interface.

Cons:
=====

* Angular features can be difficult and complex for beginners.

* Switching versions might get difficult.

* Integrating third-party libraries can be difficult.

===================================================================================
================================================================================

100) What is Angular Forms ??


========================

A) - A form provides UI that enables interaction with user.

- Form is an Element that encapsulates other elements like button, textbox,


checkbox, radio, etc....

- Angular can make a static form into Dynamic Form by using 2 different
Approaches
1. Template Driven

2. Model Driven

===================================================================================
=================================================================================

101) What is Template Driven Forms ??


================================

A) - A Template Driven Form handles all interactions in the UI.

- It comprises of Model references that are defined by using the Directives

a) ng Form : for form

b) ngModel : for form elements

- The Directive for Template form are defined in a "FormsModule" of


@angular/forms library.

Ex:
===

1. Add a new Component

> ng g templateForm --spec=false

2. templateform.component.html

<div class = "container">

<h2> Register </h2>

<form #frmRegister = "ngForm">

<dl>

<dt> User Name </dt>

<dd> <input ngModel #userName = "ngModel" name = "userName" type =


"text"></dd>

<dt> Email </dt>

<dd><input ngModel #userEmail = "ngModel" name="userEmail" type =


"email"></dd>

</dl>

</form>

</div>

===================================================================================
================================================================================
102) What is Form state validation services ??
=========================================

A) - Validation Service is a class that provides various validation properties to


verify all fields in a Form.

- The Forms state Services for validation are..

ngPristine Class --> Pristine property

ngDirty Class --> dirty property

ngValid class --> valid property

ngInValid class --> invalid property

ngSubmitted class --> submitted property

===================================================================================
=================================================================================

103) What is Input State Validation Services ??


===========================================

A) - Angular provides a set of validation services that are used to verify every
input field individually.

- The Services provide following Classes and Properties.

ngTouched --> touched

ngUnTouched -->untouched

ngPristine --> pristine

ngDirty --> dirty

ngValid --> valid

ngInValid --> invalid

errors --> errors

syntax:
=======

elementName.errors.required

elementName.invalid

===================================================================================
==================================================================================
104) What is Model Driven Forms ??
=============================

A) - A Model Driven Form is a Dynamic Form that handles all interactions at the
Controller Level.

- The library "angular/forms" provides following Classes to handle Dynamic


forms

FormGroup:
=========

It represents a base class that provides a set of properties and methods


which are used to create and configure<form> element Dynamically.

FormControl:
============

It provides a set of property and methods that are used to create and
configure any form element Dynamically.

- The Driven Forms can be configured and handled by using


"ReactiveFormsModule"

- The Dynamic form and form Elements are configured with UI by using the
properties.

1) FormGroup <form>

2) formControlName <input> <select>

Syntax:
=======

formName = new FormGroup (

controlName : new FormControl(),

controlName : new FormControl()

Note:
=====

- The Form Group Method allows to configured a set of form controls with
specified properties like value, size, class, etc...

- The Model Driven Forms Dynamically configure the controls and add to
the UI as a reference for Angular. So that it can Dynamically handle the form
elements.

===================================================================================
================================================================================

105) Explain Life Cycle Hooks ??


===========================

A) export class AppComponent {


constructor(){
//constructor will execute at booting time
//constructor will execute only once
//mainly we are using constructor for Dependency Injection
console.log("in constructor");
};

ngOnChanges(){
//it will execute after constructor
//when ever change detected in "Input" properties, then ngOnChages() life
cycle hook will execute
//Ex. cart implentation in E-Commerce Applications
console.log("in ngOnChages");
};

ngOnInit(){
//this life cycle hook called as first life cycle hook
//this life cycle will execute after ngOnChanges()
//this life cycle will execute only once
//this life cycle mainly for business logic
console.log("in ngOnInit");
};

ngAfterContentInit(){
//when ever framework identifies the memory for Component, then this life
cycle hook will be executed.
console.log("in ngAfterContentInit");
};

ngAfterContentChecked(){
//when ever memory reserved for Component, then this life cycle hook will
be executed.
console.log("in ngAfterContentChecked");
};

ngAfterViewInit(){
//when ever component is ready with all required parameters, then this life
cycle hook will be executed
//in general we will use this life cycle hook for "converting data
structures"
//Ex. @ViewChildren()
console.log("in ngAfterViewInit");
};

ngAfterViewChecked(){
//if component rendered successfully, then this life cycle hook will
execute
console.log("in ngAfterViewChecked");
};

data:number = 100;
ngDoCheck(){
//when ever change detected in bindling properties, then this life cycle
hook will be executed
//immidiately it will invokes the ngAfterContentChecked() &
ngAfterViewChecked()
console.log("in ngDoCheck");
};
increment(){
this.data = this.data+100;
}
decrement(){
this.data = this.data - 10;
};
ngOnDestroy(){
//before killing the component by framework, automatically this life cycle
hook will execute
//this life cycle hook called as last life cycle hook
//it is used to place the clean up code
console.log("in ngOnDestroy");
};

/*

constructor

ngOnChanges

ngOnInit

ngdoCheck

ngAfterContentInit

ngAfterContentChecked

ngAfterViewInit

ngAfterViewChecked

ngDoCheck

ngAfterContentChecked

ngAfterViewChecked

//change detected

ngDoCheck

ngAfterContentChecked

ngAfterViewChecked

*/

===================================================================================
============================================================================

You might also like