Angular 2 Interview Questions

Angular 2 Interview Questions

  • Sharad Jaiswal
  • 24th Sep, 2020

Angular 2 Interview Questions

1) What is Angular 2?

Angular 2 is a completely revived component-based Javascript framework in which an application is a tree of loosely coupled components. It is a more advanced version of angularJS. It is more of an "all in one" framework so it also helps in creating a single website without getting trapped into different JS frameworks. An Angular 2 is a modular framework in which our code is divided into individual procedures that offer a similar kind of functionality, hence improving the testing, up-gradation and maintenance of the application. It has a lot of useful features such as- server-side rendering, cross-platform, and supports more languages than any other framework. It is a new typescript framework built around the concept of components which is paving the way for better and spacious development. We can even make hybrid applications using Angular 2 which gives us a sharp edge by providing us the flexibility to use the same standard codes for developing other applications.

2) What is .subscribe In AngularJs?

.subscribe is not an Angular2 thing. It's a method that comes from rxjs library which Angular is using internally.

3) What is multicasting In Angular?

Multi-casting is the practice of broadcasting to a list of multiple subscribers in a single execution. Let's demonstrate the multi-casting feature,

var source = Rx.Observable.from([1, 2, 3]);
var subject = new Rx.Subject();
var multicasted = source.multicast(subject);

// These are, under the hood, `subject.subscribe({...})`:
  next: (v) => console.log('observerA: ' + v)
  next: (v) => console.log('observerB: ' + v)

// This is, under the hood, `s

4) What is Angular Material?

Angular Material is a UI component library for Angular JS developers. Angular Material components help in constructing attractive, consistent, and functional web pages and web applications while adhering to modern web design principles like browser portability, device independence, and graceful degradation.

5) What is annotation in angular?

Annotations are used to provide supplemental information about a program. Annotations do not change the action of a compiled program. Annotations help to associate metadata (information) to the program elements i.e. instance variables, constructors, methods, classes, etc.

@Component is an annotation that tells Angular, that the class, which the annotation is attached to, is a component

6) How to cache an observable data in Angular 2 ?

Caching of an observable data is done with the help of “observable.cache”. We can use caching in order to cache the response in the memory and then, on the next subscription, instead of requesting the remote server again. This operator is used at the end of the string. Caching is important for the performance, especially on bandwidth restricted devices and slow networks. You should have a good understanding of caching while working with promises but while translating it to observable, it is a bit difficult. Therefore, when interacting with observables, we typically set up a subscription on the consumer side and react to values coming through the pipe. We can easily add caching to the observables by adding publishReplay(1) and refCount.

7) List major components of Angular 2?

Components,Metadata,Modules,Services, and Templates are major components of angular 2 application.

8) Explain typings in Angular 2?

Typings describe the contract of libraries you use. This allows the TypeScript compiler that what you use exist (classes, properties, ...).

You can install typings from a repository using the typings command or let the compiler find out them leveraging the strategy specified in the tsconfig.json file with the moduleResolution attribute.

For Angular2, they (.d.ts files) are resolved within the node_modules/@angular folder since the framework contains its typings. For other libraries, like Lodash, it's not the case. So you need to install them from the repository.

To define a typings file you can leverage the export declare class clause:

export declare class SomeClass {
  name: String;
  constructor(name?: String);

9) What are hooks in Angular 2?

Hooks in Angular are functions that are called on particular stages of a component's life. There are eight main hooks for every component in Angular. They are ngOnChanges(), ngOnInit(), ngDoCheck(), ngAfterContentInit(), ngAfterContentChecked(), ngAfterViewInit(), ngAfterViewChecked(), and ngOnDestroy()

10) What is tree shaking in angular?

Tree shaking is a term commonly used in the JavaScript context for dead-code elimination. It relies on the static structure of ES2015 module syntax, i.e. import and export. The name and concept have been popularized by the ES2015 module bundler rollup.

11) What are observables in Angular?

Observables in angular are used to ensure if particular properties are being returned from API call. Observables help you manage asynchronous data, such as data coming from a backend service. Observables are used within Angular itself, including Angular’s event system and its HTTP client service. To use observables, Angular uses a third-party library called Reactive Extensions (RxJS).

12) What is Angular CLI?

Angular CLI is command-line interface for creating, updating and running Angular apps. You can install angular CLI by running npm install -g @angular/cli command.

13) Angular 2 is written in which language?

Angular 2 is written in Typescript.

14) Explain host decorator in Angular 2 ?

Host decorator in Angular tells DI (Dependency Injection) to look for a dependency in any injector until it reaches the host.

15) What is use of tsconfig.json file in Angular?

tsconfig.json file is used to provide the options for Typescript that will be used for an Angular project.

16) Which module is required for every Angular 2 app?

AppModule is required for every Angular 2 app.

17) What is a template reference variable in Angular?

A template reference variable is a reference to a DOM element within a component template. It is defined by # followed by a variable name.


<input #customerInput>

A template reference variable can be accessed anywhere in the template by variable_name.value

18) What is AOT compilation in Angular?

AOT stands for Ahead of Time. It is the compilation in which Angular compiles the components and templates to JavaScript and HTML while developing.

19) What is <ng-template>?

<ng-template> is a template element that Angular uses with structural directives (*ngIf, *ngFor, [ngSwitch] and custom directives). These template elements only work in the presence of structural directives. Angular wraps the host element (to which the directive is applied) inside <ng-template> and consumes the <ng-template> in the finished DOM by replacing it with diagnostic comments.

20) Enlist the ways components communicate with each other in Angular?

Two components in Angular can communicate via Input/Output properties, services, ViewChild/ViewContent.

21) What are shared modules in Angular?

Shared module in angular are modules that contain all the commonly used directives, pipes, and components which we want to share with other modules.

22) What is use of @RouteParams in Angular?

The @routeParams are used to map the given URL’s based on the route URLs and they become optional parameters for that route.

23) When will ngOnInit hook is called in Angular?

ngOnInit hook is called once in component life cycle after constructor(default method) and when the component is being initialized.

24) What are pure pipe and impure pipe in Angular?

Pure pipe: A Pure pipe is a pipe in Angular that is only executed when Angular detects a pure change to the input value.

Impure pipe: An impure pipe is a pip that is executed during every component change detection cycle.

25) How to intercept 404 errors in Angular 2?

You can provide a final wildcard path something like: { path: ‘**’, component: PageNotFoundComponent } in routing to intercept 404 errors in Angular.

26) What is <router-outlet> in Angular?

Router-outlet works like a placeholder in Angular which is used to load the different components dynamically based on the activated component or current route state.

27) What is RxJS?

RxJS stands for Reactive Extensions for JavaScript.It is a Javascript library for reactive programming using observables that makes it easier to compose asynchronous or callback-based code.

28) What is a template in Angular 2?

The template in Angular 2 is used to define the views of an application. A template helps us to render HTML with some dynamic parts depending on our data. It allows us to express data and property binding, event binding and templating concerns. To be able to express those behaviors, Angular 2 comes with its own symbols: {{ }} for interpolation. [] for property binding.

29) What are Wildcard Routes in Angular?

Wildcard routes in Angular are the least specific routes in the route configuration. Be sure it is the last route in the configuration. Wildcard Routes

const appRoutes: Routes = [
    { path: '**', component: PageNotFoundComponent }

30) How do you define transition between two states in Angular?

Transitions between two states take place so that we can build simple animations between two states driven by a model attribute. Transition basically means navigating from the current state to a new state. In angular, the transition is an animation-specific function which is used in angular’s animation DSL language. Transition declares the sequence of animation steps that will be executed when the entered value is satisfied. A function is provided an argument for a transition and it will be executed each time a state change occurs. In this, if the function is true, then the animation will run else it won’t get executed.

These animation transitions are placed within the animation triggers. The transition depends upon what the animation was in the previous state and what it will become in the next state. In other words, if a transition is defined that matches the old/current state criteria then the associated animation will be triggered.

function transition (stateChangeExpr: string,steps: AnimationMetadata | 
	 AnimationMetadata []):AnimationTransitionMetadata;

31) What is dynamic component in angular?

Dynamic Components are components whose location in the application is not defined at build-time and it is not used in any angular template. Instead of that these components, are instantiated and placed in the application at runtime.

32) What is JIT in Angular?

Just in time or JIT compiler is one which actually builds every time the content is requested. It is something that we use while we are developing an application. Although it is great but it has some shortcoming like the binding error in the application get discovered during runtime, the package is huge and hence the site is slow to load, etc.

33) Enlist few advantages with AOT in Angular?

Below are few benefits of AOT in Angular

  1. Faster rendering: The browser downloads a pre-compiled version of the application. So it can render the application immediately without compiling the app.
  2. Fewer asynchronous requests: It inlines external HTML templates and CSS style sheets within the application javascript which eliminates separate ajax requests.
  3. Smaller Angular framework download size: Doesn't require downloading the Angular compiler. Hence it dramatically reduces the application payload.
  4. Detect template errors earlier: Detects and reports template binding errors during the build step itself
  5. Better security: It compiles HTML templates and components into JavaScript. So there won't be any injection attacks.

34) Which module is responsible for bootstraping Angular 2 Application?

NgModule module is responsible for bootstrapping an Angular Application.

35) What is TypeScript?

Typescript is a superset of JavaScript which employs data types. Valid JS is valid TS, but not vice versa.

36) How do you create a new project from the CLI?

ng new command is used to create a new Angular project from CLI.

37) What is syntax of importing a module in Angular?

import { things } from 'wherever'; is the syntax for importing a module in Angular.

38) What is ECMAScript?

ECMAScript is a scripting language specification standardized by Ecma International in ECMA-262 and ISO/IEC 16262. It was created to standardize JavaScript to help foster multiple independent implementations.

39) What is Traceur Compiler?

Traceur is a compiler for Typescript programming language which takes Typescript classes, generators and compiles it to Javascript that our browsers understand.

40) Explain component specific hooks?

Below are some component-specific hooks in Angular

  • ngafterContentinit: It initializes the component content
  • ngAfterConctentChecked: It checks the binding of the external content.
  • ngafterViewinit: It creates the component view.
  • ngAfterviewChecked: It checks the bindings of the component’s view.

41) How to declare a component in Angular 2?

Components in Angular 2 are simply directives that are always associated with a direct template. Angular 2 components have an extremely well-defined life-cycle. When working with angular components, we can make use of interfaces that allows us to implement functionality for different times in a component's lifecycle. A component must belong to a NgModule in order for it to be usable by another component or application. Components can even control their runtime behavior by implementing various Life-cycle hooks.

The syntax for Declaring Component

@component ({selector: 'great', template: 'hello {{name}}!'})

Class greet{

      Name: string = 'world';


42) What is the use of trackBy Option for *ngFor Directive?

ngFor directive is used to iterate over a collection in Angular 2 or above.TrackBy Option with *ngFor directive is used to track which items added or removed in the collection. The trackBy function takes the index and the current item as arguments and needs to return the unique identifier for this item.

43) What are Event emitters in Angular?

EventEmitter is an Angular class which is used in components with the @Output directive to emit custom events synchronously or asynchronously and register handlers for those events by subscribing to an instance.

44) What is use of decorators used in Angular?

Angular Decorators are functions that are invoked with a prefixed @ symbol and immediately followed by a class, parameter, method or property. The decorator function is supplied information about the class, parameter or method, and the decorator function returns something in its place or manipulates its target in some way.

45) What are Pipes in Angular 2?

Pipes were earlier called filters in Angular1 and called pipes in Angular 2 and 4. It takes integers, strings, arrays, and date as input separated with | to be converted in the format as required and display the same in the browser.

Using Pipes in Angular 2

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

  selector: 'app-hero-birthday',
  template: `

The hero's birthday is {{ birthday | date }}

export class HeroBirthdayComponent {
  birthday = new Date(1988, 3, 15); // April 15, 1988

In your template

<p>The hero's birthday is {{ birthday | date }}</p>

Angular comes with a stock of pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe.

46) What is hidden property in Angular 2?

Angular 2 [hidden] is a special case binding to hidden property. It is the closest cousin of ng-show and ng-hide. It is more powerful to bind any property of elements. Both the ng-show and ng-hide are used to manage the visibility of elements using ng-hide CSS class. It is also set the display property "display: none".

47) What is ViewChild and ContentChild in Angular?

ViewChild and ContentChild in Angular:

ViewChild: It is a property decorator that configures a view query. The change detector looks for the first element or the directive matching the selector in the view DOM. If the view DOM changes and a new child matches the selector, the property is updated.

ContentChild: It is a parameter decorator that configures a content query. It is used to get the first element or the directive matching the selector from the content DOM. If the content DOM changes, and a new child matches the selector, the property will be updated.

All content queries need to be set before the ngAfterContentInit callback is called.

48) What is deep linking in Angular 2?

Deep linking in Angular is the usage of the URL, which will take to a specific page (content) directly without traversing application from the home page. It helps in getting indexed so that these links can be easily searchable by search engines like Google, Bing, Yahoo.. etc.

You can achieve deep linking in Angular 2 by using app.routes .ts file in your application. It should be injected in the app.module.ts for use and imported as well because it is not a default one in angular 2. You have to mention the routes on your view of your base component.

49) What is provider in Angular?

A provider in Angular is an instruction to the Dependency Injection system on how to obtain a value for a dependency. Most of the time, these dependencies are services that you create and provide.

A service is a particular type of provider that is declared with its class name. You declare it either in your NgModule or in a specific component simply by adding providers: [MyService] to your configuration metadata.

50) What is NgZone in Angular?

NgZone is an injectable service for executing work inside or outside of the Angular zone. The most common use of this service is to optimize performance when starting a work consisting of one or more asynchronous tasks that don't require UI updates or error handling to be handled by Angular.

51) What are directives in Angular 2?

Directives are markers on a DOM element that tell Angular to attach a specified behavior to that DOM element or even transform the DOM element and its children.

There are three types of directives in Angular:

  • Components: directives with a template.
  • Structural directives: change the DOM layout by adding and removing DOM elements.
  • Attribute directives: change the appearance or behavior of an element, component, or another directive.

52) What does Angular 2 hashtags in template mean?

It's the syntax used in the Angular 2 templating system which declares dom elements as variables.

In an Angular template, you can use data, property binding, and event binding. This is accomplished with the following syntax:

  • # It is used for variable declaration
  • () It is used for event binding
  • [] It is used for property binding
  • [()] It is used for two-way property binding
  • {{ }} It is used for interpolation
  • * It is used for structural directives

53) What is class binding in angular?

Class binding in Angular is used to set a class property of a view element. We can add and remove the CSS class names from an element's class attribute with class binding.

The class binding syntax is also like property binding. In property binding, we only specify the element between brackets. But in the case of class binding, it starts with the prefix class, followed by a dot (.), and the name of the class. You then bind the class value with CSS class name like class.class-name.

54) What is lazy loading in angular?

Lazy loading in Angular is a technique that allows you to load JavaScript components asynchronously when a specific route is activated. This can add some initial performance during the initial load, especially if you have many components with complex routing.

55) What is @ViewChild in angular?

@ViewChild is a decorator in Angular which is used to gain access to a child component, found in the template so that you can access its properties and methods.

Leave A Comment :

Valid name is required.

Valid name is required.

Valid email id is required.