Top Angular2 Interview Questions


1) What is the importance of  Package.json in Angular ?
During project Setup, a package.json file is installed with a comprehensive starter set of packages as specified in the dependencies and devDependencies sections.

dependencies and devDependencies

The package.json includes two sets of packages, dependencies and devDependencies.

The dependencies are essential to running the application. The devDependencies are only necessary to develop the application. You can exclude them from production installations by adding –production to the install command, as follows:


The dependencies section of package.json contains:

Features: Feature packages give the application framework and utility capabilities.
Polyfills: Polyfills plug gaps in the browser’s JavaScript implementation.
Other: Other libraries that support the application such as bootstrap for HTML widgets and styling.

Polyfill packages

Angular requires certain polyfills in the application environment. Install these polyfills using the npm packages that Angular lists in the peerDependencies section of its package.json.

You must list these packages in the dependencies section of your own package.json.

core-js: Patches the global context (window) with essential features of ES2015 (ES6). You may substitute an alternative polyfill that provides the same core APIs. When these APIs are implemented by the major browsers, this dependency will become unnecessary.

rxjs: A polyfill for the Observables specification currently before the TC39 committee that determines standards for the JavaScript language. You can pick a preferred version of rxjs (within a compatible version range) without waiting for Angular updates.

zone.js: A polyfill for the Zone specification currently before the TC39 committee that determines standards for the JavaScript language. You can pick a preferred version of zone.js to use (within a compatible version range) without waiting for Angular updates.

Other helper libraries
angular-in-memory-web-api: An Angular-supported library that simulates a remote server’s web api without requiring an actual server or real HTTP calls. Good for demos, samples, and early stage development (before you even have a server). Read about it in the HTTP Client page.
bootstrap: Bootstrap is a popular HTML and CSS framework for designing responsive web apps. Some of the samples improve their appearance with bootstrap.

2) What is the use of Systemjs.config.js in Angular ?
It allows to configure SystemJS to load modules compiled using the TypeScript compiler. For anonymous modules (one module per JS file), it allows to map the name of modules to JS files that actually contains the module JavaScript code.

3) What is the use of tsconfig.json in Angular ?
The presence of a tsconfig.json file in a directory indicates that the directory is the root of a TypeScript project. The tsconfig.json file specifies the root files and the compiler options required to compile the project.

A project is compiled in one of the following ways:
Using tsconfig.json

By invoking tsc with no input files, in which case the compiler searches for the tsconfig.json file starting in the current directory and continuing up the parent directory chain.
By invoking tsc with no input files and a –project (or just -p) command line option that specifies the path of a directory containing a tsconfig.json file, or a path to a valid .json file containing the configurations.

When input files are specified on the command line, tsconfig.json files are ignored.

4) What are Angular Directives ?
A directive is a class with a @Directive decorator.
A component is a directive-with-a-template; a @Component decorator is actually a @Directive decorator extended with template-oriented features.

Two other kinds of directives exist:
1) Structural directives
2) Attribute directives.

They tend to appear within an element tag as attributes do, sometimes by name but more often as the target of an assignment or a binding.

Structural Directives
Structural directives alter layout by adding, removing, and replacing elements in DOM.

 Attribute Directives
Attribute directives alter the appearance or behavior of an existing element. In templates they look like regular HTML attributes, hence the name.

The ngModel directive, which implements two-way data binding, is an example of an attribute directive. ngModel modifies the behavior of an existing element (typically an <input>) by setting its display value property and responding to change events.

 5) What are Components in Angular ?
Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components. Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.

A component must belong to an NgModule in order for it to be usable by another component or application. To specify that a component is a member of an NgModule, you should list it in the declarations field of that NgModule.

In addition to the metadata configuration specified via the Component decorator, components can control their runtime behavior by implementing various Life-Cycle hooks.

To create a component we add @Component decorator in a  class passing some parameters.

  • providers : Resources that will be injected into the component constructor.
  • selector : The query selector that will find the element in the HTML and replace by the component.
  • styleUrls : Array of path to style files.
  • template : String that contains the HTML.
  • templateUrl : path to an HTML file.

6) What’s the difference between a promise and Observable?

Both Promises and Observables will help us work with the asynchronous functionalities in JavaScript.

A Promise handles a single event when an async operation completes or fails.

-> A representation of any set of values over any amount of time.

-> 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.


  • having one pipe line
  • usually only use with async data return
  • not easy to cancel


  • are cancellable
  • are retriable by nature such as retry and retryWhen
  • stream data in multiple pipe lines
  • having array-like operations like map, filter etc
  • can be created from other sources like events
  • they are function, which could be subscribed later on

7) What is Ahead-of-Time (AOT) compiler ?

The Angular Ahead-of-Time (AOT) compiler converts your Angular HTML and Typescript code into efficient Typescript code during the build phase before the browser downloads and runs that code.

Faster Rendering
-> With AOT, the browser downloads a pre-compiled version of the application. The browser loads executable code so it can render the application immediately, without waiting to compile the app first.

Fewer Asynchronous Requests
-> The compiler inlines external HTML templates and CSS style sheets within the application JavaScript, eliminating separate ajax requests for those source files.

Smaller Angular Framework download Size
-> There is no need to download the Angular compiler, if the app is already compiled. The compiler is roughly half of Angular itself, so omitting it reduces the application size.

Detects template errors earlier
->The AOT compiler detects and reports template binding errors during the build step before users can see them.

Better Security
-> AOT compiles HTML templates and components into Javascript files long before they are served to the client. With no templates to read and no risky client-side HTML or JavaScript evaluation, there are fewer opportunities for injection attacks.

8) What are Life Cycle Hooks ?

A component has a life cycle managed by Angular. Angular creates it, renders it, creates renders it’s children, checks it when data-bound properties change, and destroys it before removing it from DOM. Angular offers life cycle  hooks which provide visibility into these key component’s events and ability to act when they occur.

Developers can tap into key moments in the life-cycle by implementing one or more of the life cycle hooks interfaces in the Angular core library. Each interface has a single hook method whose name  is the interface name prefixed with ng. For example the OnInit interface has a hook method named ngOnInit() that Angular calls shortly after creating the component.

Life-cycle Sequence 

Hook Purpose and Timing
ngOnChanges() Respond when Angular (re)sets data-bound input properties. The method receives a SimpleChanges object of current and previous property values.
Called before ngOnInit() and whenever one or more data-bound input properties change.
ngOnInit() Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component’s input properties.
Called once, after the first ngOnChanges().
ngDoCheck() Detect and act upon changes that Angular can’t or won’t detect on its own.
Called during every change detection run, immediately after ngOnChanges() and ngOnInit().
ngAfterContentInit() Respond after Angular projects external content into the component’s view / the view that a directive is in.
Called once after the first ngDoCheck().
ngAfterContentChecked() Respond after Angular checks the content projected into the directive/component.
Called after the ngAfterContentInit() and every subsequent ngDoCheck().
ngAfterViewInit() Respond after Angular initializes the component’s views and child views / the view that a directive is in.
Called once after the first ngAfterContentChecked().
ngAfterViewChecked() Respond after Angular checks the component’s views and child views / the view that a directive is in.
Called after the ngAfterViewInit and every subsequent ngAfterContentChecked().
ngOnDestroy() Cleanup just before Angular destroys the directive/component. Unsubscribe Observables and detach event handlers to avoid memory leaks.
Called just before Angular destroys the directive/component.

9) What are modules ?

Angular modules are containers for different parts of the app.

A module is a class with @NgModule decorator. To create a module we add @NgModule passing some parameters.

  • bootstrap:  The component that will be the root of the application. This configuration in only present on the root module.
  • declarations : Resources the module declares. When new component is added this array has to be updated.
  • exports : Resources the module exports that can be used in other modules.
  • imports : Resources the module uses from other modules (only module classes are accepted)
  • providers : Resources that can be injected in a component.

10) What are pipes ?

The pipe | character is used to apply pipes in Angular 2. Pipes are very similar to filters in AngularJS in that they both help to transform the data into a specific format.

11) Explain Observables ?
-> An observable is a representation of any set of values over any amount of time.
-> Observables provide support for passing messages between publishers and subscribers in the application.  Publisher creates an observable instance that defines a subscriber function. This is the function that is executed when a consumer calls the subscribe() method. The subscriber function defines how to obtain or generate values or messages to be published.

12) What is zone and What is the use of NgZone?
-> A zone is basically an execution context for asynchronous operations.
-> Zones wrap asynchronous browser APIs and notify a consumer when an asynchronous task has started and ended.
-> Angular takes advantage of these APIs to get notified when any asynchronous task is done. This includes things like XHR calls, setTimeout() and user events like click, submit, mousedown etc.
-> Once notified, Angular knows that it has to perform change detection because any of the asynchronous operation might have changed the application state.
-> The nice thing about this is that developers don’t have to care about notifying Angular to perform change detection, because Zones will do it for us as Angular subscribes to them under the hood.
-> Change detection is performed whenever an asynchronous event happened and an event handler is bound to that event.
-> NgZone enables us to explicitly run certain code outside Angular’s zone., preventing Angular to run any change detection.

-> Different Javascript frameworks have different methods of refreshing the UI when a data state changes.
-> ReactJS uses setState() method from the Component class to know that a property in the state object is being updated

-> AngularJS uses Scopes and Digest. Scopes are like plain JS objects but have added functionality that enables it to watch data properties for changes.
-> In Angular, Zone.JS is used to detect when certain async operations occur to trigger a change detection cycle.

-> Zone.js is an execution context that helps developers intercept and keep track of async operations. Zone works on the concept of associating each operation with a zone. Each zone can fork and create a child zone with a different context, no limits.

13) How would you protect a component being activated through the router?
-> Create a guard service:

-> this will created auth.guard.ts

-> Create canActivate() or canActivateChild() methods
-> Use the guard when defining routes

14) What is the difference between @ViewChild() and @ContentChild() ?
-> ViewChild : The child element which is located inside the component template.
-> Any directive, component and element which is part of component template is accessed as ViewChild.
-> Any element or component which is projected inside <ng-content> is accessed as ContentChild

15) What is content projection ?
-> Content projection is used to project content in a component.
-> It allows you to insert a shadow dom in the component.

16) What is a template variable. How would you use it ?
-> Template variable creates a reference to a DOM within a template.
-> We can declare reference variable by using the hash symbol (#). Scope for this variable is the entire HTML template in which the reference is defined.

-> We can use that reference to get the value of input as below.

-> It can also be used with Components and Directives.

-> We can now get a reference to that component as follows, using the “hashtag syntax”:

-> And the best part of it is that we’re getting a reference to the actual component instance, HelloWorldComponent, so we can access any methods or properties of that component (even if they are declared as private or protected, which is surprising):

17) What are different ways of Data Binding in Angular ?
1) Interpolation
2) Property Binding
3) Event Binding
4) Two-way Binding

18) What is Interpolation ?
-> Interpolation is a technique that allows the user to bind a value to a UI element.
-> It binds the data in one-way. This means that when value of the field bound using interpolation changes, it is updated in the page as well.
It cannot change the value of field.

19) How Property Binding can be done ?

20) What is the use of RxJS library ?
-> RxJS is a library for building asynchronous applications with observable sequences.

21) What are the building blocks of RxJS ?
-> Observables
-> Observers
-> Subscriptions
-> Operators
-> Subjects
-> Schedulers

22) What is an observer ?
-> An observer is an object with simple interface and contains below methods

23) What are the different categories of operators in RxJS?
-> Transformation
-> Filtering
-> Combination
-> Utitity
-> Conditional
-> Aggregate
-> Multicasting

24) What is a Subject in RxJS ?
-> They are both Observables and  Observers.
-> They can produce values.
-> They have state and maintain a list of observers.


Leave a Reply

Your email address will not be published. Required fields are marked *