Top Angular Interview Questions and answers would help freshers and experienced candidates clear any Angular interview .Do let us know the Angular questions you faced in the interview that are covered ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Angular Interview Questions & Answers
1. Angular Interview Q's
1) What is Angular? Advantages and Disadvantages?
Ans)
Angular is a Javascript binding framework which helps to bind HTML UI
with Javascript objects.
It is used to create single page web applications.
Angular 2 is completely rewrite of Angular 1.
It is component based architecture.
It supports across all platforms
It uses dependency injection and make use of separation of concerns
It is integrated with ReactJS extension (RxJS).
It supports more languages JavaScript(ES5, ES6), TypeScript & Dart.
No controllers and scope like Angular 1
2) Difference between AngularJS and Angular?
Ans)
Angular :-
----------
1) Component based development With Object Oriented Programming is
Possible.
2) Datatype Support with Compile time type Checking is Possible.
3) Can be used for both Server Side as well as Client Side Programming.
4)Angular Supports JavaScript/TypeScript/EcmaScript 5/6.
5)Angular 2 is mobile-oriented.
Angular JS :-
-------------
1) Component based development With Object Oriented Programming is not
Possible.
2) No DataType Support, with Compile time type Checking is not Possible.
3) Can be used for only Client Side Programming.
4) AngularJS Supports only JavaScript/EcmaScript 5.
5) Angular Js was not built with mobile support .
2. Angular Interview Q's
3) What is NPM?
Ans) NPM Stands for Node Package Manager
NPM is a command line interface program to manage node.js libraries such as
package installation, version management, and dependency management.
4) What is CLI? What are the steps to setup AngularCLI?
Ans) It is a command line interface to scaffold and build angular apps using nodejs style
modules and it is used for creating big angular projects.
Node and npm: npm install -> node –v & npm –v
Typescript: npm install –g typescript -> for checking: tsc –v
Angular cli: npm install –g @angular/cli -> for checking: ng –v
5) What are the core concepts of Angular?
Ans) Core Concepts:-
-------------------
Components are heart of entire Angular application.
Component is a simple class which is associated with angular template and
business logic.
component = template + business logic + metadata
Templates are nothingbut HTML code along with Angular API
Modules are similar to packages in other programming languages
Data binding is communication between component to template/view page
Structural Directives are nothing but for loop, if block and switch cases in JS & TS
Dependency Injection means Inject the objects in to other components
Services are business logic and also to communicate with server side technologies
Pipes are used to format the data
6) What is Module/@NgModule in Angular?
Ans)
Modules are blocks ofcode whichare usedfor doingspecific task.
AngularModules consolidate components,directives, pipes andservices into cohesive
blocks offunctionality.
It is similar to packages in other programminglanguages like Java
Every Angularapp has at least onemodule, the root module, conventionally named
AppModule
@NgModule annotation is whatactually defines the module
3. Angular Interview Q's
7) Diff b/w declarations,imports,providers in module?
Ans)
@NgModule consisting mainly 3 parts:
1. Declarations: wecan list the components,directives andpipes that are part ofthe
module in the declarations array
2. Imports:we canimport other modules by listing them in the imports array
3. Providers:wecanlist the services that are partof the module in the providers array
8) What is binding in angular?
Ans) Data binding is the communication or synchronization of data between the model and
view components.
There are 4 types of bindings:
1. Property binding- communcationfromcomponentto view/template
2. Event Binding – communicatinfromview/template to component
3. Class Binding – Class level binding
4. Style Binding – Style (Inline) level binding
9) Explain about Property Binding with example?
Ans) Property binding is a one-way data binding from data source (Component) to view
target(Template). This is similar to innerHtml concept in html & JS.
Note: It is Indicated by [ ] square Brackets.
Example:
import { Component } from '@angular/core';
@Component({
selector: 'racha-component',
template: `<h1>{{title}}</h1>
<img [src] = "myImage">`
})
export class RaChaComponent {
public myImage = "http://charanIInfo.com/images/slides/logo.jpg";
}
4. Angular Interview Q's
10) Explain about Event Binding with example?
Ans) Event binding is a one-way data binding from view target(Template) to data source
(Component).
Note: It is Indicated by ( ) parenthesis.
Example:
import { Component } from '@angular/core';
@Component({
selector: 'racha-component',
template: `UserName: <input type="text" #userInput><br/><br/>
<button (click)="onClick(userInput.value)">Click Here</button>`,
})
export class RaChaComponent {
onClick(value:any) {
alert(value)
}
}
11) What is Directive? What are the advantages?
Ans) It Changes the Dom layout by adding, removing, appearance and behavior of Dom
elements.
Angular provides 3 types of directives: component, attribute and structural
directive
Components— It is used to create HTML template
Structural directives—It changes the DOM layout by adding and removing DOM
elements.
Attribute directives—It changes the appearance and behavior of DOM element
Note: We can create custom directive using @Decorator annotation.
12) What are structural Directives? Explain briefly?
Ans) Structural directives —>It changes the DOM layout by adding and removing of DOM
elements.
Example:
import { Component } from '@angular/core';
@Component({
selector: 'racha-component',
template: `<div *ngIf="showElement">Show this content</div>
5. Angular Interview Q's
<div [ngSwitch]="course">
<p *ngSwitchCase="'java'">Java course selelected</p>
<p *ngSwitchCase="'angular'">Angular course selelected</p>
<p *ngSwitchDefault>Invalid Course</p>
</div>
<ul>
<li *ngFor="let name of names">{{name}}</li>
</ul>`
})
export class RaChaComponent {
public showElement:boolean = true;
public course:string = "angular";
public names:string[] = ['charan','naresh','pavan','kumar'];
}
13) What is component? Explain with example?
Ans) Components are one of the core concepts in Angular.
Component is a simple class which is associated with angular template and business logic.
component = template + business logic +metadata
Note: template is nothingbut HTML code along with Angular API
If we want to create new component, we have to use @Component annotation.
Rules for Component:
1) Create the component
2) Registration of the component in app.module.ts file (@NgModule registration)
3) Consume (Access) the component in template/html.
Example:
Step1: Create of component.
racha.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'racha-component',
template: `<h1>RaCha component result</h1>`,
styles: [`h1{color:orange}`]
})
export class RaChaComponent { }
6. Angular Interview Q's
Step2: Registration of the component
Note: We need to import and register above component in app.module.ts
import {RaChaComponent } from './racha.component'
declarations: [RaChaComponent ]
Step3: Access the component
app.component.ts
import { Component } from '@angular/core';
import {RaChaComponent } from './racha.component'
@Component({
selector: 'app-root',
template: `<h1>App component result</h1>
<racha-component></racha-component>`
})
export class AppComponent { }
Note: app.component styles are wrtten by default in style.css in src folder.
14) Differences between Components and Directive?
Ans) Directives:
The mechanism by which we attach behaviour to elements in the DOM,
consisting of Structural, Attribute and Component types.
Components:
The specific type of directive that allows us to utilize web component
functionality - encapsulated, reusable elements available throughout our
application.
15) What is template/ng-template in Angular?
Ans) Templates are nothingbut HTML code along with Angular API
Templates= HTML code + Angular API
16) Difference between template & templateURL?
Ans) template:-
-------------
1) template can be used to specify inline markup.
2) template doesn't provide intelligence and auto-completion.
3) template can't be reusable.
7. Angular Interview Q's
templateUrl:-
----------------
1) templateUrl can be used to specify markup with in html file.
2) templateUrl will provide intellisense and auto-completion.
3) templateUrl can be reusable across many components.
17) Difference between styles & stylesURL?
Ans) styles : -
---------
1) styles can be used to specify the inline style to component.
2) styles doesn't provide intellisense and auto-completion.
3) styles can't be reusable.
stylesUrl : -
-------------
1) stylesUrl can be used to specify component style within css files.
2) stylesUrl provide intellisense and auto-completion.
3) stylesUrl can be reusable through components.
18) What is attribute directive? What are the types?
Ans) Attribute directives—It changes the appearance and behavior of DOM element.
They are two types
1) ngStyle
2) ngClass
Example:
import { Component } from '@angular/core';
@Component({
selector: 'racha-component',
template: `
<div [ngClass]="['bold-text', 'mygreen']">array of classes</div>
<div [ngClass]="'italic-text myblue'">string of classes</div>
<div [ngClass]="{'small-text': c1, 'red': c2}">object of classes</div>
<div [ngStyle]="{'color': col, 'font-size': font}">style using ngStyles </div>
`,
styles:[]
})
export class RaChaComponent {
public c1: boolean = true;
public c2: boolean = true;
public col:string = 'red';
9. Angular Interview Q's
20) What is the life cycle of component?
Ans) A component has a lifecycle managed by Angular itself. Angular manages
creation, rendering, data-bound properties etc. It also offers hooks that allow us to
respond to key lifecycle events.
Here is the complete lifecycle hook interface inventory:
ngOnChanges - called when an input binding value changes
ngOnInit - after the first ngOnChanges
ngDoCheck - after every run of change detection
ngAfterContentInit - after component content initialized
ngAfterContentChecked - after every check of component content
ngAfterViewInit - after component's view(s) are initialized
ngAfterViewChecked - after every check of a component's view(s)
ngOnDestroy - just before the component is destroyed
21) What is @input and @output decorators?
Ans) @Input:
-------------
@Input decorator binds a property within one component (child
component) to receive a value from another component (parent component).
This is one way communication from parent to child.
@Output:
-------------
@Output decorator binds a property of a component to send data from one
component (child component) to calling component (parent component).
This is one way communication from child to parent component
22) How to communicate components?
Ans) Three Ways of Implementing This Behavior:
Passing the Reference of One Component to Another
Communication Through Parent Component
Communication Through Service
10. Angular Interview Q's
1) Passing the reference of one component to another:
This solution should be used when components have dependency between them.
For example dropdown, and dropdown toggle. They usually can’t exist without
each other.
We will create the side-bar-toggle component which will have the side-bar
component as input and by clicking on the toggle button we will open/close
the side-bar component.
Example:
app.component.html:
app component
<app-side-bar-toggle [sideBar]="sideBar"></app-side-bar-toggle>
<app-side-bar #sideBar></app-side-bar>
side-bar-toggle.component.ts:
@Component({
selector: 'app-side-bar-toggle',
templateUrl: './side-bar-toggle.component.html',
styleUrls: ['./side-bar-toggle.component.css']
})
export class SideBarToggleComponent {
@Input() sideBar: SideBarComponent;
@HostListener('click')
click() {
this.sideBar.toggle();
}
}
side-bar.component.ts:
@Component({
selector: 'app-side-bar',
templateUrl: './side-bar.component.html',
styleUrls: ['./side-bar.component.css']
11. Angular Interview Q's
})
export class SideBarComponent {
@HostBinding('class.is-open')
isOpen = false;
toggle() {
this.isOpen = !this.isOpen;
}
}
2) Communication through parent component:
Can be used when it’s easy to control shared state between components
through their parent component and you don’t feel like you want to create new
service or create some boilerplate code, because of one variable.
Implementation of this approach is almost the same as the previous one,
however side-bar-toggle doesn’t receive side-bar component. Instead parent
component holds sideBarIsOpened property which is passed to the side-bar
component.
Example:
app.component.html:
<app-side-bar-toggle (toggle)="toggleSideBar()"></app-side-bar-toggle>
<app-side-bar [isOpen]="sideBarIsOpened"></app-side-bar>
app.component.ts:
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
sideBarIsOpened = false;
toggleSideBar(shouldOpen: boolean) {
this.sideBarIsOpened = !this.sideBarIsOpened;
}
12. Angular Interview Q's
}
side-bar-toggle.component.ts:
@Component({
selector: 'app-side-bar-toggle',
templateUrl: './side-bar-toggle.component.html',
styleUrls: ['./side-bar-toggle.component.css']
})
export class SideBarToggleComponent {
@Output() toggle: EventEmitter<null> = new EventEmitter();
@HostListener('click')
click() {
this.toggle.emit();
}
}
side-bar.component.ts:
@Component({
selector: 'app-side-bar',
templateUrl: './side-bar.component.html',
styleUrls: ['./side-bar.component.css']
})
export class SideBarComponent {
@HostBinding('class.is-open') @Input()
isOpen = false;
}
3)Communication through service:
Finally this option is useful and should be used when you have component
that is controlled or its state is asked from multiple instances.
In this example neither side-bar component or side-bar-toggle component
has input parameters, because they communicate through service.
14. Angular Interview Q's
constructor(
private sideBarService: SideBarService
) { }
ngOnInit() {
this.sideBarService.change.subscribe(isOpen => {
this.isOpen = isOpen;
});
}
}
side-bar.service.ts:
@Injectable()
export class SideBarService {
isOpen = false;
@Output() change: EventEmitter<boolean> = new EventEmitter();
toggle() {
this.isOpen = !this.isOpen;
this.change.emit(this.isOpen);
}
}
23) What is service in angular?
Ans) SERVICES:
Service is a singleton class with specific purpose/task.
The main advantage of service is Reusability
We should Implement Business logic in side service.
Access to shared data
Through services also we can communicate from one component to other
External Interactions (interacting with server side technologies)
Pre-defined services like $http, ...etc
24) What are the steps to create service?
Ans) Step 1: Define/create the EmployeeSerive class
Step 2: Register the service with injector
Step 3: Declare as dependency in EmpList and EmpDetail
15. Angular Interview Q's
25) How to consume services in components?
Ans)
Import the service to your Component
Ex: import { EmployeeService } from './employee.service';
Add it as a provider
Ex:
@Component({
selector: 'app-root',
template: `<h2>RaCha Infotech</h2><hr/>
<employee-list></employee-list>`,
providers: [EmployeeService]
})
Include it through Dependency Injection
Ex: constructor(private employeeService:EmployeeService){ }
Invoke the service related methods
Ex: employeeService.getEmployees();
Include/register the service in app.module.ts
Ex:
import { EmployeeService } from './employee.service';
@NgModule({
// put all your services here
providers: [EmployeeService ],
})
26) What is Dependency Injection (DI)?
Ans) Dependency Injection means Inject the objects in to other components.
Angular creates services(No need to use the new operator)
Angular Injects Objects into Components Via Constructor
Providers Specifies how to inject the objects
The main advantage of Dependency Injection is writing code in loosely
coupled way and makes our code more testable and reusable.
Sometimes one service may inject into other service
16. Angular Interview Q's
27) What is HTTP Service?
Ans) HTTP :
-------------
In order to start making HTTP calls from our Angular app we need to import
the angular/http module and register for HTTP services. It supports both
XHR and JSONP requests exposed through the HttpModule and
JsonpModule respectively. In this section we will be focusing only on the
HttpModule.
28) What are predefined Pipes in angular?
Ans)
29) What is Pipe? What are the advantages of Pipes?
Ans) Pipes:
Pipes are used to transform and format our data
Angular provides built-in pipes like Date, UpperCase, LowerCase,
Currency, Async, Decimal, Percent, JSON, Slice ...etc.
We can also create parameterized and chaining pipes.
17. Angular Interview Q's
Syntax: {{ myValue | myPipe1 | myPipe2 }}
30) How to create custom pipe?
Ans) CUSTOM PIPE CREATION:
Step 1: import Pipe, PipeTransform from angular core package.
Step 2: Decorate the class using @Pipe.
Step 3: Implement PipeTransform interface for our typescript class.
Step 4: Override transform() method.
Step 5: Configure the class in application module with @NgModule.
31) How to create template driven form in angular?
Ans) Template Drive Forms are just Model Driven Form but driven by directives in
the template versus code in the component.
In template driven we use directives to create the model.
In model driven we create a model on the component and then use directives to map
elements in the template to our form model.
App.component.html:
<div class="container">
<h2>User Registration Form</h2>
<form #userForm = "ngForm" (ngSubmit)="onSubmit(userForm.value)">
<div class="form-group">
<label>Name:</label><input type="text" #nameRef="ngModel" required
minlength="5" maxlength="9" pattern="[a-z]+" class="form-control" name="name"
ngModel>
<!--<b>{{nameRef.className}}</b>-->
<!--<div [hidden]="nameRef.valid || nameRef.pristine" class="alert alert-danger">
Please Enter Name
</div>-->
<div *ngIf="nameRef.errors && (nameRef.dirty || nameRef.touched)" class="alert
alert-danger">
<div [hidden]="!nameRef.errors.required">
Please Enter a Name
</div>
<div [hidden]="!nameRef.errors.minlength">
Please Enter atleast 5 characters
</div>
<!-- maxlength validation not required bcz we are not allowed to enter more than
that.-->
<div [hidden]="!nameRef.errors.pattern">
Please Enter valid data
19. Angular Interview Q's
}
32) Diff between template and model driven forms?
Ans) Template Driven Forms, or the Angular 1 way
Model Driven Forms, or the new Functional Reactive way
Template Driven Forms Features:
------------------------------------------------------
Easy to use
Suitable for simple scenarios and fails for complex scenarios
Similar to AngularJS
Two way data binding(using [(NgModel)] syntax)
Minimal component code
Automatic track of the form and its data(handled by Angular)
Unit testing is another challenge
Model-Driven /Reactive Forms Features:
-------------------------------------------------------
More flexible, but needs a lot of practice
Handles any complex scenarios
No data binding is done (immutable data model preferred by most
developers)
More component code and less HTML markup
Reactive transformations can be made possible such as
Handling a event based on a debounce time
Handling events when the components are distinct until changed
Adding elements dynamically
Easier unit testing
33) What is routing and how to use routing in angular?
Ans) Routing is used to navigate from one view/component to other view/component
Steps:
1.Set the base Tag in index.html file
<base href="/">
2.Import RouterModule
import { RouterModule } from '@angular/router';
3.Configure routes
declarations: [AppComponent, WebComponent, JavaComponent],
RouterModule.forRoot([
20. Angular Interview Q's
{path:'web', component: WebComponent},
{path:'java', component:JavaComponent}
])
4.RouterLink and RouterLinkActive directives binding
5.Components get rendered between this tag. <router-outlet> </router-outlet>
34) Diff between observable and promises?
Ans) Promise:
--------------
A Promise handles a single event when an async operation completes or fails.
Note: There are Promise libraries out there that support cancellation, but ES6
Promise doesn't so far.
Observable:
----------------
An Observable is like a Stream (in many languages) and allows to pass zero or
more events where the callback is called for each event.
Often Observable is preferred over Promise because it provides the features of
Promise and more. With Observable it doesn't matter if you want to handle 0,
1, or multiple events. You can utilize the same API in each case.
Observable also has the advantage over Promise to be cancelable. If the result
of an HTTP request to a server or some other expensive async operation isn't
needed anymore, the Subscription of an Observable allows to cancel the
subscription, while a Promise will eventually call the success or failed callback
even when you don't need the notification or the result it provides anymore.
Observable provides operators like map, forEach, reduce, ... similar to an array
There are also powerful operators like retry(), or replay(), ... that are often
quite handy.
21. Angular Interview Q's
35) Explain Angular Framework Architecture with the help of diagram?
Ans) Angular is a framework as well as a platform for building client applications in
HTML and TypeScript.
Angular is one of the leading frameworks preferred by web developers around the
world. As such, it is a lucrative option to add to your programming arsenal.
Architecture:
36) Briefly explain Angular 2 Metadata?
Ans) Description:
----------------
Metadata is a way of processing the class and a component called
MyComponent will act as a class until we tell Angular that it's a component.
User can use metadata to the class to tell Angular that MyComponent is a
component. Metadata can be attached to TypeScript using a decorator.
Annotations :−
-------------------
22. Angular Interview Q's
These are decorators at the class level. This is an array and an example having
both the @Component and @Routes decorator.
app.component.ts file:-
@Component ({
selector: 'my-app',
templateUrl: 'app/app.component.html'
})
The component decorator is used to declare the class in the app.component.ts file as
a component.
37) What is Traceur compiler?
Ans) Traceur compiler:
The Traceur is a JavaScript compiler. The Traceur compiler used to
allow us to use the features from the future. The Traceur compiler is
fully supported to ECMAScript(ES6) and ES.vNext also.
The main goal of Traceur compiler is to inform the designs of new
JavaScript features and also allow us to write the code in better
manners and it also prefer, tell us to use design patterns.
Now the days Traceur compiler are broadly used in Angularv2.0
because Angular v2.0 are fully used to ES5 and ES6.
38) What is AOT Compilation?
Ans) Ahead-of-Time (AOT) compiler:
The Angular Ahead-of-Time (AOT) compiler converts your Angular HTML
and TypeScript code into efficient JavaScript code during the build phase
before the browser downloads and runs that code. Compiling your application
during the build process provides a faster rendering in the browser.
This guide explains how to specify metadata and apply available compiler
options to compile your applications efficiently using the AOT compiler.
39) Difference between JIT (Just-in-time )and AOT(Ahead-of-Time)?
Ans) JIT - Compile TypeScript just in time for executing it.
Compiled in the browser.
Each file compiled separately.
23. Angular Interview Q's
No need to build after changing your code and before
reloading the browser page.
Suitable for local development.
JIT compilation is the default when you run the ng build (build only) or ng serve (build and
serve locally) CLI commands:
ng build
ng serve
AOT - Compile TypeScript during build phase.
Compiled by the machine itself, via the command line (Faster).
All code compiled together, inlining HTML/CSS in the scripts.
No need to deploy the compiler (Half of Angular size).
More secure, original source not disclosed.
Suitable for production builds.
AOT compilation, include the --aot option with the ng build or ng serve command:
ng build --aot
ng serve --aot
40) What are new features of Angular 4,5,6,7?
Ans)
new in Angular 4:
Router ParamMap:
Starting from version 4, it is possible to use paramMap to get the route- and
query-parameter from a related route. The use of Map brings advantages in
terms of type security.
The old had an unsecure type (type params = {[key: string]: any}) and the
value could have all possible types.
The new way provides either a string, or an array of strings related to the used
method (paramMap.get(): string and paramMap.getAll(): string[])
Animations:
Earlier all the functions of animations were the part of @angular/core
module, which means the code were always included in the bundle even if
animations were not used.
24. Angular Interview Q's
In Angular 4, Animations are to be provided in the module
BrowserAnimationsModule from @angular/platform-browser/animations.
This avoids creating bundles with unnecessary large sizes.
ngif:
We can now use new if/else style syntax with *ngif structural directive.
NgComponentOutlet:
To build and produce components dynamically at runtime involved relatively
much programming work. With the introduction of *ngComponentOutlet-
Directive in Angular 4, it is possible to build dynamic components in a
declarative way.
TypeScript 2.1/2.2:
We have the support of most latest TypeScript versions in Angular 4 which
helps in improving the speed of ngc-Compiler.
Angular Universal:
With Angular Universal, it is possible to render Angular applications on the
web server. With that, websites can be optimized better for search engines as
JavaScript is no longer necessary for initially rendering the page content.
new in Angular5:
Angular 5 supports Typescript version 2.4
Angular 5 supports RxJS 5.5 which has new features like Pipeable Operators
A build tool to make the js bundles (files) lighter
Ahead of Time (AOT) is updated to be on by default
Events like ActivationStart and ActivationEnd are introduced in Router
new in Angular6:
1. Angular Elements
2. Service Worker Support
3. Bye, Bye Template Element
25. Angular Interview Q's
4. i18n
5. Ivy: New Rendering Engine
6. ngModelChange
7. ElementRef<T>
8. Bazel Compiler
9. RxJS 6.0
10. Tree Shaking
new in Angular7:
CLI Prompts:
Application performance:
Angular Material & the CDK
Virtual Scrolling
Drag and Drop
Angular Compatibility Compiler (ngcc)
Angular Do-Bootstrap
Better Error Handling
Dependency Updates In Angular 7
TypeScript 3.1 support
RxJS 6.3
Added Support for Node v10
Angular Elements with Slot
New ng-compiler.
Splitting of @angular/core
Router
Still no Ivy
Documentation updates
Deprecations
update to Angular7 Commands:
npm install -g @angular/cli@latest`
$ ng updates @angular/cli @angular/core
$ng update @angular/material