ANGULAR 8 Interview Questions
ANGULAR 8 Interview Questions
Answers ==========
*******************************
===================================================================================
==========================================================================
===================================================================================
===========================================================================
===================================================================================
============================================================================
- cli is the tool used to build and execute the angular applications.
===================================================================================
===========================================================================
===================================================================================
============================================================================
===================================================================================
===========================================================================
===================================================================================
==========================================================================
===================================================================================
==========================================================================
Example:
-------
logos, XML files, json files, fonts, custom fonts ....... and so on.
===================================================================================
===========================================================================
===================================================================================
==========================================================================
===================================================================================
==========================================================================
Example:
--------
jQuery, ReactJS, d3JS, underscorejs,------and so on.
===================================================================================
============================================================================
===================================================================================
============================================================================
===================================================================================
=============================================================================
===================================================================================
==========================================================================
A) - selector is the json key used to define the custom HTML element.
===================================================================================
========================================================================
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.
===================================================================================
========================================================================
A) - It specifies the name and path of style sheet. That contains the styles used
for component.
===================================================================================
===============================================================================
Note ===> - Angular 3 was never initiated and released due to "Routing"
improvements.
===================================================================================
=================================================================================
===================================================================================
============================================================================
Module : ngx-toastr
> yarn add ngx-toastr --save
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()
]
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"
]
===================================================================================
==========================================================================
- Receiving the continuous data from server, (when ever updates available) called
as Observable.
===================================================================================
=============================================================================
1) Manual Testing
2) Automation Testing
1) Unit Testing
2) Integration Testing
> ng test
Note : unit test cases file should end with ".spec" extension
===================================================================================
==========================================================================
- 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.
===================================================================================
==========================================================================
===================================================================================
============================================================================
predefined pipes
----------------
=> uppercase
=> lowercase
=> titlecase
=> date
=> currency
=> json
=> percent
=> number
=> slice
=> async
===================================================================================
==============================================================================
- Pipe is the predefined class used to assign the logical name to Custom Pipe.
===================================================================================
=================================================================================
@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.
===================================================================================
================================================================================
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.
1) predefined services
2) custom services
- HttpClient is the predefined service, used to make the Rest API Calls.
===================================================================================
=================================================================================
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
Angular 4:
===========
1) Angular 4 is the rewrite version of angular 2 but is it added with the feature
of backward compatibility
3) Angular 4 is backward compatible with the Angular 2 framework for most of the
applications.
Angular 6:
==========
1) Angular 6 is the advanced version of Angular 4 which is faster and easy to use
the framework.
5) The typescript ES6 and 2.4 are used by this framework of angular.
Angular 8
=========
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.
===================================================================================
===============================================================================
Differential loading:
======================
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.
Bazel:
======
It is a building tool through which angular developer can build backends and
frontends.
===================================================================================
============================================================================
- Whenever you want to control over the resolvers and guards, use
runGuardsAndResolvers option in Angular 8.
===================================================================================
=============================================================================
===================================================================================
=================================================================================
A) A few of the major advantages of using Angular framework are listed below:
----------------------------------------------------------------------------
===================================================================================
==========================================================================
===================================================================================
===
A) 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-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:
===============
<ng-content></ng-content>
(The content inside the selector tags will be rendered in place of the <ng-
content> in the above component HTML)
<angular-questions>
</angular-questions>
<angular-questions>
</angular-questions>
===================================================================================
============================================================================
- Angular is one of the most popular Javascript Frameworks for building web
applications.
3) Cross-Platform
4) Reduced Coding
5) Modularity in Angular
Versions of Angular
===================
Angular 2
Angular 4
Angular 5
Angular 6
Angular 7
Angular 8
Angular 9
1) Paypal
2) Upwork
3) Netflix
4) Freelancer
===================================================================================
================================================================================
===================================================================================
==========
A) BrowserModule :
---------------
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 HttpClient is more modern and easy to use the alternative of HTTP.
===================================================================================
============================================================================
- To add optional parameters follow the pipe name with a colon (:).
- Its looks like- currency: 'INR'
===================================================================================
=============================================================================
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.
===================================================================================
==============================================================================
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
-> 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".
===================================================================================
===============================================================================
A) - In one-way Binding the model data is updated to the view but any change in the
View will not update the Model.
Note:
=====
Interpolation will not use any property Binding. It Binds value to any attribute
directly by using "{{}}" databinding expression.
===================================================================================
=================================================================================
A) - The two-way data binding technique allows the changes in View to update in
the Model.
- The directive "ngModel" is responsible for handling the property and event
binding for any specific element.
syntax:
=======
[(ngModel)] = "property"
===================================================================================
=================================================================================
- Angular provides built in validation services that are categorized into Twi
types
===================================================================================
===============================================================================
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.
===================================================================================
=================================================================================
A) - Transpiling means compilation of one High Level Language into another High
Level Language.
- But our browser understands only the JavaScript, which again a High Level
Language.
===================================================================================
================================================================================
43) How to communicate between the parent and child component in angular ??
=========================================================================
- @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.
- @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.
===================================================================================
===============================================================================
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.
<base href="/">
- Its to be placed in the index.html head tag (main HTML file for angular
application)
===================================================================================
=================================================================================
A) - Singleton services are the services which are only initialized once in a
application.
- Means only one time memory is given, and it retains the same memory for the
entire application.
@Injectable({
providedIn: 'root',
})
export class DemoService {
}
===================================================================================
=================================================================================
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
===================================================================================
============================================================================
A) BrowserModule:
=============
CommonModule:
=============
===================================================================================
===============================================================================
48) What is the use of forRoot() method in angular ??
===================================================
- forRoot() and forChild() are static methods that configure services in the
root and feature modules respectively.
===================================================================================
===================================================================================
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.
===================================================================================
===================================================================================
=
Shared Module:
==============
Featured Module:
================
===================================================================================
=================================================================================
A) ==> HttpClient is the angular inbuilt service used to handle HTTP request in
angular.
==> HttpClient offers a simplified client HTTP API for Angular applications that
rests on the XMLHttpRequest interface exposed by the browsers.
===================================================================================
===================================================================================
=
A) --> Http are introduced at the staring of angular to handle HTTP request
response.
===================================================================================
=================================================================================
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.
At route:
=========
===================================================================================
=================================================================================
providers
declarations
imports
exports
entryComponents
bootstrap
schemas
id
@NgModule({
providers?: Provider[]
id?: string
})
===================================================================================
=================================================================================
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.
===================================================================================
===================================================================================
==> RouterLinkActive takes css, which it sets to the link, which is currently
active.
<a routerLink="/category/mobile">Mobile</a>
<a routerLink="/category/tablet">Tablet</a>
</div>
===================================================================================
=================================================================================
Example to use :
================
@Component({templateUrl:'dritalconnect.html'})
class MyComponent {
constructor(router: Router) {
}
}
===================================================================================
===================================================================================
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.
NavigationStart
RouteConfigLoadStart
RouteConfigLoadEnd
RoutesRecognized
GuardsCheckStart
ChildActivationStart
ActivationStart
GuardsCheckEnd
ResolveStart
ResolveEnd
ChildActivationEnd
ActivationEnd
NavigationEnd
NavigationCancel
NavigationError
Scroll
===================================================================================
===================================================================================
interface ActivatedRoute {
snapshot: ActivatedRouteSnapshot
url: Observable<UrlSegment[]>
params: Observable<Params>
queryParams: Observable<Params>
fragment: Observable<string>
data: Observable<Data>
outlet: string
root: ActivatedRoute
pathFromRoot: ActivatedRoute[]
paramMap: Observable<ParamMap>
queryParamMap: Observable<ParamMap>
toString(): string
===================================================================================
================================================================================
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 kept at the last of the of the routes array.
--> Wild card route should be only one in the whole application.
===================================================================================
=================================================================================
===================================================================================
=============================================================================
===================================================================================
============================================================================
63) How to navigate to another routing in typescript ??
===================================================
A) this.router.navigate(['/another-path']);
===================================================================================
============================================================================
1. CanActivate :
------------------
2. CanDeacticate :
------------------
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
4. CanActivateChild :
--------------------
===================================================================================
=================================================================================
A) When we need to pass the constraint data from the router, we need to define
in the route.
In Routing:
===========
constructor(
private route: ActivatedRoute
) {}
ngOnInit() {
this.route.paramMap.pipe(
switchMap(params => {
this.mobileId = params.get('id');
})
);
}
}
===================================================================================
================================================================================
A) 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.
===================================================================================
==============================================================================
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.
===================================================================================
=============================================================================
===================================================================================
============================================================================
A) Using ActivatedRoute:
======================
@Component({
templateUrl: './demo.component.html'
})
export class DemoComponent implements OnInit {
public pageTitle: string;
ngOnInit(): void {
this.pageTitle = this.route.snapshot.data['title'];
}
}
===================================================================================
=================================================================================
- 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
===================================================================================
=============================================================================
===================================================================================
===================================================================================
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
"compilerOptions": { ... },
"angularCompilerOptions": {
"enableIvy": true
===================================================================================
===================================================================================
===================================================================================
================================================================================
suitable to the type The following list of decorators comes under class
decorators,
@Component()
@Directive()
@Pipe()
@Injectable()
@NgModule()
===================================================================================
==============================================================================
===================================================================================
==============================================================================
===================================================================================
====================================================================
import { HttpRequest,
HttpHandler,
===================================================================================
===========================================================================
Example:
=========
===================================================================================
================================================================================
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
===================================================================================
================================================================================
- 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
- 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.
===================================================================================
===============================================================================
A) You can get a handle to the DOM element via ElementRef by injecting it into your
component's constructor:
===================================================================================
==============================================================================
interface Observer<T> {
closed?: boolean;
}
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.
===================================================================================
================================================================================
Ex:
---
setTimeout(() => {
}, 2000);
});`
===================================================================================
===============================================================================
===================================================================================
============================================================================
<router-outlet></router-outlet>
===================================================================================
===========================================================================
A) The RxJS library also provides below utility functions for creating and
working with observables.
- Filtering streams
===================================================================================
=======================================================================
A) Angular expressions are code snippets that are usually placed in binding such
as {{ expression }} similar to JavaScript.
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
===================================================================================
==============================================================================
===================================================================================
==============================================================================
- Angular uses all Javascript browser Events, which are categorized into
a) Key Events
b) Mouse Events
c) Miscellaneous Events
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.
===================================================================================
===============================================================================
- The style object is binded to any element by using the Directive [ngStyle].
Syntax:
-------
.ts
====
public ApplyColor(){
let obj = {
'color' : this.colorName
return obj;
}
.html
=====
===================================================================================
==================================================================================
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.
===================================================================================
================================================================================
A) - Angular can use the browser mouse events that are used to handle various
interaction with ragard to mouse functionality.
specifies actions to perform while mouse pointer is moving over any element.
mouseover
=========
mouseout
========
mousedown
=========
mouseup
=======
===================================================================================
===================================================================================
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
keyup
keydown
keypress
===================================================================================
==============================================================================
96) What is Nested Components ??
============================
A) - A component in angular can use any another component within the content.
of "angular/core" library.
Example:
=======
2. Go to child.component.ts
3. Go to child.component.html
</h2>
4. Go to parent.component.ts
5. Go to parent.component.html
===================================================================================
==============================================================================
Creating a component
Rendering a component
===================================================================================
================================================================================
- Angular provides EventEmitter base class that have set of properties and
methods for creating a custom event.
- Angular can use Custom Events for its components, which are defined by using
EventEmitter.
Syntax:
======
public onMyEvent() {
this.myEvent.emit(stringValue);
</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:
======
* 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.
* React Native is used to build native mobile apps with existing React
knowledge.
Pros:
=====
Cons:
=====
Pros:
=====
Cons:
=====
===================================================================================
================================================================================
- Angular can make a static form into Dynamic Form by using 2 different
Approaches
1. Template Driven
2. Model Driven
===================================================================================
=================================================================================
Ex:
===
2. templateform.component.html
<dl>
</dl>
</form>
</div>
===================================================================================
================================================================================
102) What is Form state validation services ??
=========================================
===================================================================================
=================================================================================
A) - Angular provides a set of validation services that are used to verify every
input field individually.
ngUnTouched -->untouched
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.
FormGroup:
=========
FormControl:
============
It provides a set of property and methods that are used to create and
configure any form element Dynamically.
- The Dynamic form and form Elements are configured with UI by using the
properties.
1) FormGroup <form>
Syntax:
=======
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.
===================================================================================
================================================================================
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
*/
===================================================================================
============================================================================