Angular Interview Questions & Answers

💡 What is ng-template in Angular?

ng-template is a template element that is used with structural directives like *ngIf, *ngFor, [ngSwitch], and custom directives that we create.

<div *ngIf="showTemplate">This is First Template</div>

So what happens here, Actually Angular converts the above structural directive to the below ng-template code:

<ng-template [ngIf]= "showTemplate">
 <div>This is First Template</div>

💡 How can we manually use *ngIf with ng-template?

The below code will not work.

<ng-template *ngIf="showTemplate">This is template</ng-template>

✔ The correct way to use *ngIf with ng-template is given below –

showTemplate = true; // is TS file

<ng-template *ngIf="showTemplate then goToTemplateOne"></ng-template>
<ng-template #goToTemplateOne>This is template</ng-template>


<ng-template [ngIf]= "showTemplate">
 <div>This is template one</div>

💡 What is the use of ng-container?

The Angular is a grouping element that does not create any instance in DOM, and also can’t be styled or layout. Mostly we use ng-container when we have to work with two structural directives.

<div *ngFor="let item of items" >
	<div *ngIf="item.itemId">{{item.itemName}}</div>

Note that, this code will work fine but it introduces several extra empty div in the DOM if is a falsy value which might not be required.

✔ Best way to write the above code.

<ng-container *ngFor="let item of items">
<div *ngIf="item.itemId">{{item.itemName}}</div>

Read here more –

💡 What is ng-content?

This is used for Content Projection and to create configurable components.

💡 How can we do multiple projections using ng-content?

We can control multiple content projection with the select attribute of ng-content. It takes an element selector to decide which content to project inside a particular ng-content.

💡 Explain ngTemplateOutlet?

ngTemplateOutlet is a directive that inserts an embedded view from a prepared TemplateRef.
What this means is that in the child component we can get a template from the parent component and we can inject a context object into this template.

*ngTemplateOutlet is a highly customized component. We can also render the default template if we don’t pass from the parent component that we can not do with ng-content.

💡 How to convert promise into Observable?

The RxJS Observable interface provides the toPromise() method that can be used to get a promise from the Observable.

💡 Is NgZone (zone.js) is required for change detection in Angular?

Yes, Zone and NgZone are used to automatically trigger change detection as a result of async operations. But since change detection is a separate mechanism it can successfully work without Zone and NgZone.

💡 How can we run Change Detection without zone.js?

To remove zone dependency from the Angular app, we can comment below line from the polyfils.ts file.

import 'zone.js/dist/zone';

After that, We’ll configure Angular to use the noop Zone implementation like this –

    .bootstrapModule(AppModule, {
        ngZone: 'noop'

Now if we run our app then we can see that automatic change detection stops working. To trigger it manually, we have to inject ApplicationRef and triggering tick method to start change detection.

constructor(app: ApplicationRef) {
   = 'updated';
        }, 1000);

💡 How can we execute an external API in the Angular zone to read change detection?

If we implemented google login or FB login APIs, so we can not access angular change detection inside its methods because it runs outside Angular Zone. To make it work we use method to call that code inside the Angular zone. => { 
	// your code

💡 What is Resolver in Angular and how to implement this?

One way to display data from an API is to route a user to that component, and in that component’s ngOnInit hook, call a method from a service to get the necessary data. While getting the data, a component can show a loading indicator.

✔ Another best approach is route resolver, which allows you to get data before navigating to the new route.

To Create a Resolver service we create a class that implements Resolve (from ‘@angular/router‘) and decorated by @Injectable(). resolve method is necessary to implement this.

import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';

export class ItemResolver implements Resolve<any> {
 //  inject service from where we have to fetch data
  constructor(private itemService: ItemService) {}

  resolve() {
    return this.itemService.getItems();

Define this in the routing module file:

    path: 'itemList',
    component: ItemComponent,
    resolve: { itemData: ItemResolver }

✔ We can access this in Component with ActivatedRoute.

constructor(private route: ActivatedRoute) {}
ngOnInit() { =;

💡 What is an async pipe?

Async pipe is used when we subscribe an Observable into an HTML template directly.

[person]="(person$ | async)?.profile">

Every time we use the async pipe, we create a subscription. If you’re going to subscribe directly to Observables (see above code line) that initiate data transfer, you can face some unwanted issues and flaws such as duplicate data or multiple HTTP requests.

✔ Best way to use: async with ngIf –

<div *ngIf="(person$ | async) as person; else loading">

<ng-template #loading>
  Loading stuff...

Instead of waiting for each person$ | async operation to be fully available. What this will do is wait until (person$ | async) has evaluated, and bind the result to the value of the person.
And the second advantage is we can also use else condition here to show the loading indicator.

💡 Is Observable is an Angular term?

The Observable isn’t an Angular-specific feature, but a new standard for managing async data that will be included in the ES7 release.
Observables are lazy in the sense that they only execute values when something subscribes to them.

💡 What are Cold Observable and Hot Observable?

An Observable is cold when data is produced inside the Observable and the Observable is hot when the data is produced outside the Observable.

 import * as Rx from "rxjs";

**Cold Observable**

const coldObservable = Rx.Observable.create((observer) => {; // produce different values for each subscriber.

**Hot Observable**

const random = Math.random() // produce same result fo each subscriber.
const hotObservable = Rx.Observable.create((observer) => {;

In Cold Observable, For each subscriber, the Observable produce a different result. We call this behavior “unicasting”.
On another side, the hot Observable is able to share data between multiple subscribers because we have computed results outside. We call this behavior “multicasting”.

💡 What is wrong with the below code?

    .map(params => params['id'])
    .switchMap(id => {
      if(id !== null && id !== undefined) { 
        return this.getUser(id)
    .subscribe(user => this.user = user);

An Observable is kept alive until it completes. In the above example, if there is no id passed to the switchMap, the Observable never completes. Don’t leave your Observables hanging there. Correct way to do this –

    .map(params => params['id'])
    .switchMap(id => {
      if(id !== null && id !== undefined) { 
        return this.getUser(id)
      } else { 
        return Observable.empty()
    .subscribe(user => this.user = user);

Here Observable.empty() completes the Observable stream.

💡 What will be the output of the below code?

const numberPromise = new Promise((resolve) => {

numberPromise.then(value => console.log(value));

// it will print only 5.

Promises are most commonly used to handle HTTP requests. In this model, you make a request and then wait for a single response. You can be sure that there won’t be multiple responses to the same request.

💡 What will be the output of the below code?

const numberObservable = new Observable((observer) => {;;

numberObservable.subscribe(value => console.log(value));

// prints 5 and 10

Observables allow you to resolve multiple values or we can say it can emit more than one value.

💡 Explain Promise are eager and Observable are lazy with a code example?

const promise = new Promise(() => {
    console.log('I was called!');

const observable = new Observable(() => {
    console.log('I was called!');

In the case of Promise, this will print “I was called!” to the console immediately. This happens because the Promise constructor immediately calls the function passed to it.

With Observable, this time nothing happens. This is because while Promises are eager, Observables are lazy. The function passed to Observable constructor gets called only when someone actually subscribes to an Observable.

💡 tabIndex vs tabindex in angular?

By convention, HTML attributes use lowercase names (tabindex), while properties use camelCase names (tabIndex).

💡 What is the difference between query parameter and path parameter?

It is very important to know when to use Query Parameter or path parameter (URI Parameter) while designing an API.
Path parameters are used to identify a specific resource or resource such as a user identified by ID. You can’t omit values in path parameters since they are part of the URL. Secondly, the query parameters are used to sort/filter resources.

Let’s consider an example where you want to identify the employee on the basis of employeeID, and in that case, you will be using the URI param.

GET /employee/{employeeID}

Take another example where you want to filter the employee on the basis of designation, and in that case, you will be using Query Parameter.

GET /employee?designation=SSE

💡 Difference between the below two codes?

this.router.navigate(['/articles', {id: 1}]);

this.router.navigate(['/articles', id]);

✔ {id: 1} in [‘/articles’, {id: 1}] is an optional route parameters and added as matrix parameters to child routes and query parameters to the root route.

✔ [‘/articles’, id] is a normal and required route parameter that replaces :id in the route path.

💡 What is the difference between static true and false in ViewChild?

✔ Use { static: true } when you want to access the ViewChild in ngOnInit. it is also available in ngAfterViewInit.
✔ Use { static: false } will be accessible only in ngAfterViewInit, not in ngOnInit. This is also what you want to do when you have a structural directive (*ngIf etc.) in your template.

@ViewChild('elementA', { static: true }) elementStatic: ElementRef<HTMLElement>;
@ViewChild('elementB', { static: false }) elementDynamic: ElementRef<HTMLElement>;

public ngOnInit(): void {
 this.elementStatic.nativeElement; // Ok
 this.elementDynamic.nativeElement; // ERROR TypeError: Cannot read property 'nativeElement'of undefined 
public ngAfterViewInit(): void {
    this.elementStatic.nativeElement; // Ok
    this.elementDynamic.nativeElement; // Ok

💡 Is angular2 mvc?

Angular 2 is more of a component-based architecture. You can assume everything as a component, like directives, services, and so on. While directives and services are actually for the support of base components, they are also defined in a similar fashion. A base component contains dependencies, view details, and a class declaration which may be considered as a controller. So, a well-defined component contains one set of MVC architecture.


✔ Why Angular is a Preferred Choice for Developers? Top Features

✔ Web Application Security Best Practices | Top Tips to Secure Angular App

✔ What’s new in Angular 9 | Top updates in Angular 9 By JS mount

✔ What’s new in Angular 8 | Angular 8 Latest Feature By JS mount

✔ Best Practices for Writing Angular Apps | Angular Guidelines

✔ NgRx Top Interview Questions and Answers You should know

✔ Tips to Boost Angular App Performance | Web page Speed Optimization

✔ Angular NgModule, AOT, and DI, and EntryComponents with example

✔ Angular Dependency Injection Provider and Types of Provider

✔ Rx JS Top Operators with examples | Rx JS interview questions

✔ Prime NG Row Group with Subheader and Totals Row

✔ How to implement Reactive Form with Prime NG table

✔ Angular Auto Tab Directive : Auto focus on next field

✔ Dynamic Tooltip with Angular Pipe: Performance Orientation

✔ Angular Create a Custom directive to match password and confirm password

Angular Interview Questions & Answers

Leave a Reply

Your email address will not be published.