Angular 2 Interview Questions

Angular 2 Interview Questions and Answers

Angular 2 is the upgraded and evolved version of AngularJS, a JavaScript framework that was developed by Google. Our recently updated Angular 2 Interview Questions can help you crack your next interview. Angular 2 is used for building single-page web or mobile applications. Written in TypeScript, Angular implements core functionalities as TypeScript libraries that get imported into apps. AngularJS is known for intuitive HTML and amazing new features where developers are free to use ngIf and ngRepeat, modular design and various other built-in functionalities.

About Angular 2
What is Laravel Angular 2 is the upgraded and evolved version of AngularJS, a JavaScript framework that was developed by Google. Angular 2 is used for building single-page web or mobile applications.
Latest Version 7.2.x and released in October 18, 2018
Created By Google
Written in TypeScript
Official Website https://angular.io/

One of the unique features of the Angular 2 framework is that it is designed in such a way that each component is independently testable, using different methods. Angular 2 is mostly a rewrite of the first version to avoid its faults. We have an impressive collection of Angular 2 Interview Questions that is a must read for all developers and designers!. One of the most significant advantages of Angular 2 is that it offers more language choices such as TypeScript, ES6, Dart and ES5 for writing codes.

Liked the content, and wish to know more interview questions of the different versions of Angular, find the solutions below-

Development History

Google originally developed AngularJS in 2009, and its first version was released in 2012. Since then AngularJS has been the leading open-source JavaScript framework until later versions were launched. This is the most frequently asked Angular 2 Interview Questions.

Advantages of Angular 2 Programming Language

Angular 2 has the following advantages over its predecessor:

  • Code is simpler
  • Faster rendering
  • Built with mobile devices in mind
  • Better performance
  • Easier to read and learn
  • Simplified architecture because it is component-based

Latest Version

Angular 2 was released in September 2016. Google released AngularJS 1.7.5 in October 2018.

Angular 2 Interview Questions and answers

Looking for a new job? Do not miss to read our Angular 2 Interview Questions and answers. Whether you are a fresher or an experienced, these questions and answers that can help you to crack your interview.

Angular 2 is the upgraded and evolved version of AngularJS, a JavaScript framework that was developed by Google. Angular 2 is used for building single-page web or mobile applications.


Components are eseential elements of Angular 2 apps, and an application can have a number of components. In Angular 2, components perform all the tasks that were done by scopes, controllers and directives, such as creating or adding Data, logic and custom elements.


In Angular 2 an component consists of the following:

  • Template
  • Class
  • Metadata


The three steps to creating a component asre as follows:

  • Create class and export it.
  • Decorate class with @component metadata.
  • Libraries and modules can be imported.

Directives are the extended HTML attributes and they are also the most important features of Angular applications. They introduce syntax or markup.

There are 3 kinds of directives - Components, Structural and Attribute.

This information is likely to be asked in angular 2 interview questions

The Router enables viewers to navigate from one view or page to the next as they perform application tasks. Routing assists users based on the option they select on the main web page. Based on user options, the Angular Component renders to the user.

  Angular 1 Angular 2
1. No mobile support Mobile-oriented
2. Only supports Dart, ES6 and ES5 Offer more language choices
3. Easy to set up Dependent on libraries. Requires efforts to set up.
4. Based on controllers and scope Component-based.
  • Avoid injecting dynamic Html content
  • Sanitize external HTML
  • Do not put external URLs in the application
  • Use AOT compilation
  • Prevent XSRF attack by restricting api

Using angular routing you can navigate from one view or page to another while performing your tasks. You can configure a URL to redirect to the next URL. This feature can be handled to address the "404 Not Found" problem. Using location services in Angular routing you can go back and forward through the history of pages.

Syntax : We can use {path: '/OUR_PATH', redirectTo: ['redirectPathName']}



{path: '/404', name: 'PageNotFound', component: NotFoundComponent}

All Angular 2 apps have the option of finding and handling errors. This can be done by including the ReactJS catch library and using the catch function.



We have add this code in the product.service.ts file
import { Injectable } from '@angular/core';
import { Http , Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import { IProduct } from './product';

export class ProdService {
   private _producturl = 'app/products.json';
   constructor(private _http: Http){}

   getproducts(): Observable {
       return this._http.get(this._producturl)
       .map((response: Response) => response.json())
       .do(data => console.log(JSON.stringify(data)))

   private handleError(error: Response) {
      return Observable.throw(error.json().error());

In all Angular version from 2 onwards, there is a common feature called Pipes. This feature helps developers create custom pipes.

Pipes are used to write display-value transformations that developers can declare in their HTML. A pipe inputs data and transforms it in the required output.

Lazy loading allows developers to load different code pieces on demand. For instance, if you have a retail application that has different departments like garments, groceries, electronics, etc. If you load all the sections in the beginning, your application will be slow. This is when you need lazy loading. It helps application load faster because it loads only parts that the user wants to see.

You can implement lazy loading in 4 steps:
  • Update route file.
  • Get angular-router-loader and add it to your config file
  • Define lazy routes
  • Import routes to the module.

Any change that occurs in the component gets propagated from the existing component to its children. If this change needs to be reflected its parent component, you can use using Event Emitter api to emit the event.

EventEmitter is class in @angular/core module that is used by directives and components to emit events.

@output() somethingChanged = new EventEmitter();

You can use somethingChanged.emit(value) to emit any event. You can do this in setter when the value is changed in the class.

  Components Directive
1. To register, use @Component meta-data annotation To register, use @Directive meta-data annotation
2. Used to create UI widgets and break up app into smaller components Use to design re-usable components and add behavior to existing DOM element.
3. Only one component allowed per DOM element Many directives allowed per DOM element.
4. @View decorator is mandatory Does not use View.

The simplest way is to put the variables in a file and export them. In order to use global variables, you can use an import statement.


   // ===== This File is as globalfile.ts

// 'use strict';

export const name='bestinterviewquestion.com';


After that we can export this file where we want to use these global variables value.
import * as myGlobalsFile from './globalfile';

You can do this through property binding feature in Angular2. In order to bind data to components, you need to create a custom property bind. This can create it via “input” binding for passing data from one component to another. You can create the custom input binding via the @Input() decorator!

  Promise Observable
1. Have one pipeline Pass data in multiple pipelines
2. Only used with async data return Could be subscribed later on
3. Not easy to cancel Cancellable

Here are the steps:

  • Import injectable member
  • Add @Injectable Decorator
  • Export Service class


Here is the syntax:

import { Injectable } from '@angular/core';
   export class MyCustomService {

In Angular 2, you can create custom pipes. The simplest way is as follows.

import { Pipe, PipeTransform } from '@angular/core';
    @Pipe({name: 'Pipename'})
    export class Pipeclass implements PipeTransform {
    transform(parameters): returntype { }

In the above code,

//   Pipename' is pipe's name.
//   Pipeclass is class that is assigned to custom pipe.
//   Transform is the function that works with custom pipe.
//   Parameters are the parameters that get passed to the pipe.
//   Returntype is the return type of the custom pipe.

This information is trending in angularjs 2 interview questions for experienced professionals.

In Angular 2, styles or styleUrls affect the style of template elements. The built-in properties in the component Decorator allow developers to encapsulate styles directly as part of their components.


Both style and styleUrls are arrays, which means that for styles, you can apply many definitions for each position. For styleUrls, you can split up different style rules into different style sheets.

It is a command line interface which is used to build angular apps. We can construct & start a project very quickly with the help of CLI.

You can download CLI from its official website https://cli.angular.io

The command for install Angular CLI

npm install –g angular-cli

  @Injectable @Inject
1. Aims to set metadata of dependencies to be injected into constructor Tells Angular what parameter must be injected
2. Without it, no dependency can be injected Only needed to inject primitives

The Angular Ahead-of-Time (AOT) compiler converts Angular HTML and TypeScript codes into JavaScript code during the build phase before the browser can download and run the code.

Here are benefits of compiling with AOT:

  • Fast rendering
  • Lesser asynchronous requests
  • Smaller download size of Angular framework
  • Detects errors easily
  • Improved security
  • Fast download
  • Quicker rendering
  • Reduces Http Requests
  • Catches errors during the build phase
  • Only works with HTML and CSS; Not other file types.
  • Must maintain bootstrap file AOT version
  • Must clean-up before compiling.

These features stand out:

  • Use of TypeScript
  • Built-in support for mobile app development
  • Improved performance
  • Support for 3 directives types - component, decorator, and template.
  • Enhanced Dependency Injection
  • Increased data binding
  • Supports component-based architecture
  • Cross-platform and cross-browser support

It is an open source tool for running and checking if the pre-defined coding guidelines were followed or not. It does static code analysis for typescript and angular projects.

It runs on top of tslint and coding conventions are defined in tslint.json file. Editors such as Visual Studio Code support codelyzer by doing basic settings.

The biggest benefit of TypeScript is tools like advanced autocompletion, refactoring and navigation. Because of TypeScript developers do not need to rewrite to migrate to JavaScript. They can do it one module at a time. In addition, because of TypeScript, the code is easier to understand.

In Angular 2, a module groups the various components, pipes, directives, and services in a way that assists them in combining with other modules for creating an application.

A module can be used to hide or export pipes, directives, components and services.

An observable is an array where data arrives asynchronously.

Observables can help developers manage asynchronous data and are used within Angular, including event system and HTTP client service. Angular uses Reactive Extensions (RxJS), a third-party library, to use Observables.

Decorators allow developers to configure classes as elements by putting metadata on them.

The most common decorators are @Component one for components and @Injectable one for classes.

Decorators are new in TypeScript, and were not available in AngularJS. Angular2 onwards offers four types of decorators and each plays a unique role - Class, Property, Method, and Parameter.

Services allow greater separation of concerns in Angular applications. They also provide modularity by allowing developers to extract common functionalities out of components. Adding Services to Angular applications makes components free from data access code.


Service has the following features:

  • Singleton, i.e. only one instance of service will exist throughout the application.
  • Capable of returning data in the form of Observables and promises.
  • Decorated with @Injectable() decorator

Cookies are packages of information that are stored by the browser from websites that use cookies for multiple uses.

There are two ways to create cookies:

  • Inject service in components providers.
  • Get it via npm.

In order to set cookies, you can use the following method:

// the put method takes in the name of the cookie and the value for that cookie.

// if we wanted to define cookie options then we would pass in a third parameter to

// this method containing those options.

this._cookieService.put('test', 'test');

It configures the injector and compiler, and assists in organizing things together. This class is marked by the @NgModule decorator. It can identify module's directives, components, and pipes, making them public as required through the exports properties so that they can be used by the external components.

Ask Question