Angular

Best Angular Interview Questions and Answers

Are you preparing for your Angular Developer Interview? If yes then, Congratulations! You have successfully made your way to this article. We all know that Technical Interview is one of the most crucial stages of your final selection process for an Angular Developer. Therefore, here are some of the most commonly asked angular interview question which you don’t want to miss out.

Note: In many organizations, there is also some sort of coding test in addition to the technical round, so make sure to keep up your programming practice for the interview. If you are looking for some good angular coding problems, you can check this article out.

Angular Interview Questions

Without wasting any more time, let’s dive into some of the most important and commonly asked Angular interview questions which will be helpful to everyone whether you are a fresher or an experienced one.

Table of Contents

Question: What is Angular Framework?

Answer: Angular Framework is a TypeScript-based open-source web application framework. It is developed and maintained by the Angular Team at Google and by a community of individuals and corporations. Angular is a complete rewrite from the same team that built AngularJS.

Some of the major features of this framework like declarative templates, dependency injection, end to end tooling, and many more really help the developer in facilitating the front end development.

Question: Describe the pictorial architecture of Angular?

Answer: The architecture of angular consists of the eight main building blocks of an Angular application that are as follows – Modules, Components, Templates, Metadata, Data binding, Directives, Services, and Dependency injection. Here is the pictorial representation of the Angular Architecture.

Angular Interview Questions with Answers

Question: What is the difference between angular and Angularjs?

Answer: Angular is a completely revived component-based framework that is derived from AngularJs. AngularJS utilizes HTML as a template language. By extending HTML attributes with directives and binding data to HTML with expressions, AngularJS creates an environment that is readable, extraordinarily expressive and quick to develop.

Meanwhile Angular is the blanket term used to refer to Angular 2, Angular 4 and all other versions that come after AngularJS. Both Angular 2 and 4 are open-source, TypeScript-based front-end web application platforms.

Read more: Difference Between Angular and AngularJS

Angular AngularJS
This is based on Service/Controller It is based on MVC architecture
Introduced the typescript to write the application This uses use JavaScript to build the application
This is a component-based UI approach Based on controllers concept
Developed considering mobile platform Not a mobile-friendly framework
Ease to create SEO friendly applications Difficulty in SEO friendly application development
This is based on Service/Controller It is based on MVC architecture
This is based on Service/Controller It is based on MVC architecture
This is based on Service/Controller It is based on MVC architecture

Question: What is TypeScript in Angular?

Answer: TypeScript is one of the most popular open-source programming languages. It is developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing to the language which provides it the functionality of having optional types, classes, async/await, and many other features, and compiles to plain JavaScript.

Angular built entirely in TypeScript and used as a primary language for Angular application development. It is a superset of JavaScript with design-time support for type safety and tooling.

Question: What are the key or basic components in Angular?

Answer: Angular Framework consists of eight basic building blocks or key component which are as follows:

  1. Component: These are the basic building blocks of angular application to control HTML views.
  2. Modules: An angular module is a set of angular basic building blocks like component, directives, services, etc. An application is divided into logical pieces and each piece of code is called “module” which performs a single task.
  3. Templates: This represents the views of an Angular application.
  4. Services: It is used to create components that can be shared across the entire application.
  5. Metadata: This can be used to add more data to an Angular class.
  6. Data binding: Data binding is a continuous synchronization of data from view to the component and component to the view.
  7. Directives: A directive is a custom HTML element that is used to extend the power of HTML.
  8. Dependency Injection: Dependencies are services or objects that a class needs to perform its function.

Question: What are the advantages and disadvantages of Angular Framework?

Answer: Here are the advantages and disadvantages of using Angular Framework

Advantage of using Angular Framework

  1. Angular provides the ability to add a custom directive.
  2. Angular Framework has exceptional community support.
  3. With an angular framework, it is easy to facilitate client and server communication.
  4. Inbuilt support for features like Animation and Event Handlers.
  5. It follows the MVC pattern architecture.
  6. Offers support for static template and Angular template.
  7. Support for two-way data-binding.
  8. Supports dependency injection, RESTful services, and validations.

The disadvantage of using Angular Framework

  1. Complex SPAs can be inconvenient and laggy to use due to their size.
  2. Dynamic Applications do not always perform well.
  3. The learning curve of the Angular framework is slightly long.

Question: What is template in Angular?

Answer: In Angular Framework, a template is an HTML snippet or view that tells Angular how to render the component in angular application. In Template, you can display data by binding controls to properties of an Angular component.

You can also store your component’s template in one of two places. You can define it inline using the template property, or you can define the template in a separate HTML file and link to it in the component metadata using the @Component decorator’s templateUrl property. Using the inline template with template syntax. Here are examples of both cases.

Using the inline template:

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

@Component ({
   selector: 'my-app',
   template: '
      <div>
         <h1>{{title}}</h1>
         <div>Learn Angular</div>
      </div>
   '
})

export class AppComponent {
   title: string = 'Hello World';
}

Using a separate template files. Forex – app.component.html

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

@Component ({
   selector: 'my-app',
   templateUrl: 'app/app.component.html'
})

export class AppComponent {
   title: string = 'Hello World';
}

Question: What is template expression in Angular?

Answer: A template expression produces a value similar to any Javascript expressions. In Template Expression, Angular executes the expression and assigns it to a property of a binding target which might be an HTML element, a component, or a directive.

In the property binding, a template expression appears in quotes to the right of the = symbol as in [property]=”expression”. Whereas, In interpolation syntax, the template expression is surrounded by double curly braces. For example, in the below interpolation, the template expression is {{username}}.

<h3>{{username}}, welcome to Angular</h3>

It must be noted that some of the javascript expressions are prohibited to use in template expression which are as follows:

  1. assignments (=, +=, -=, …)
  2. New
  3. Chaining expressions with ; or ,
  4. Increment and decrement operators (++ and –)

Question: What is template statements in Angular?

Answer: A template statement in Angular response to an event raised by a binding target such as an element, component, or directive. The template statements appear in quotes to the right of the = symbol like (event)=”statement”. Here is an example of a template statement in angular.

<button (click)="editProfile()">Edit Profile</button>

Question: What are the components in angular?

Answer: Components are the most basic building block of an Angular app which formed a tree of Angular components. These 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. Let’s see a simple example of an Angular component.

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

@Component ({
   selector: 'my-app',
   template: ` <div>
      <h1>{{title}}</h1>
      <div>Learn Angular6 with examples</div>
   </div> `,
})

export class AppComponent {
   title: string = 'Welcome to Angular world';
}

A component is made up of a selector, template, style and other properties, using which it specifies the metadata required to process the component. The @Component decorator identifies the class immediately below it as a component class and specifies its metadata.

Question: What is Module in angular?

Answer: Angular apps are modular in nature and to facilitate this Angular has its own modularity system called NgModules. NgModules are containers for a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities.

In a simpler language, Modules are logical boundaries in your application and the application is divided into separate modules to separate the functionality of your application. Let’s take an example of app.module.ts root module declared with @NgModule decorator as below.

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';

@NgModule ({
   imports:      [ BrowserModule ],
   declarations: [ AppComponent ],
   bootstrap:    [ AppComponent ]
})
export class AppModule { }

Modules can contain components, service providers, and other code files whose scope is defined by the containing NgModule. Using module you can also import functionality that is exported by some other NgModules, and export selected functionality for use by other NgModules.

Question: What is Metadata in angular?

Answer: Metadata is used to decorate a class so that it can configure the expected behavior of the class. The metadata is represented by decorators. A decorator is a function that has a configuration object. Here are some of the commonly used decorators in angular

Class decorators, e.g. @Component and @NgModule

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

@Component({
  selector: 'my-component',
  template: '<div>Class decorator</div>',
})
export class MyComponent {
  constructor() {
    console.log('Hey I am a component!');
  }
}

@NgModule({
  imports: [],
  declarations: [],
})
export class MyModule {
  constructor() {
    console.log('Hey I am a module!');
  }
}

Property decorators Used for properties inside classes, e.g. @Input and @Output

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

@Component({
    selector: 'my-component',
    template: '<div>Property decorator</div>'
})

export class MyComponent {
    @Input()
    title: string;
}

Method decorators Used for methods inside classes, e.g. @HostListener

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

@Component({
    selector: 'my-component',
    template: '<div>Method decorator</div>'
})
export class MyComponent {
    @HostListener('click', ['$event'])
    onHostClick(event: Event) {
        // clicked, `event` available
    }
}

Parameter decorators Used for parameters inside class constructors, e.g. @Inject

import { Component, Inject } from '@angular/core';
import { MyService } from './my-service';

@Component({
    selector: 'my-component',
    template: '<div>Parameter decorator</div>'
})
export class MyComponent {
    constructor(@Inject(MyService) myService) {
        console.log(myService); // MyService
    }
}

Question: What are services in angular?

Answer: Service is any value, function, or feature that an app needs. A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well. An Angular service contains methods that maintain the data throughout the life of an application.

The primary intent of an Angular service is to organize as well as share business logic, models, or data and functions with various components of an Angular application. The functions offered by an Angular service can be invoked from any Angular component, such as a controller or directive.

Services allow for greater separation of concerns for your application and better modularity by allowing you to extract common functionality out of components. Angular distinguishes components from services to increase modularity and reusability.

By separating a component’s view-related functionality from other kinds of processing, you can make your component classes lean and efficient. Here is the example of service in angular.

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable({ // The Injectable decorator is required for dependency injection to work
  // providedIn option registers the service with a specific NgModule
  providedIn: 'root',  // This declares the service with the root app (AppModule)
})
export class RepoService{
  constructor(private http: Http){
  }

  fetchAll(){
    return this.http.get('https://api.github.com/repositories');
  }
}

Question: What is Data binding in angular?

Answer: Data Binding is a feature of angular framework which helps to connect application data with the DOM (Data Object Model). It happens between the template (HTML) and component (TypeScript).

Question: How many types of Data Binding is there in Angular?

Answer: In Angular, there are 3 methods or ways in which data binding can be achieved, each of which differs in the way the data is flowing.

Event Binding – It enables the application to respond to user input in the target environment. When a specific DOM event happens (eg.: click, change, keyup), call the specified method in the component.

<button (click)="logout()"></button>

Property Binding – It enables the interpolation of values computed from application data into the HTML. The value is passed from the component to the specified property or simple HTML attribute.

<input type="email" [value]="user.email">

Two-way Binding – Changes made in the application state get automatically reflected in the view and vice-versa. The ngModel directive is used for achieving this type of data binding – [(ngModel)]=”value”. Two-way data binding allows having the data flow both ways. For example, in the below code snippet, both the email DOM input and component email property are in sync.

<input type="email" [(ngModel)]="user.email">

Question: What is Dependency Injection in angular?

Answer: Dependency injection is an important application design pattern in which a class asks for dependencies from external sources rather than creating them itself. It means that objects do not create other objects on which they rely to do their work. Instead, they get these objects from an outside source.

Angular comes with its own dependency injection framework for resolving dependencies( services or objects that a class needs to perform its function). So you can have your services depend on other services throughout your application. Here is an example of dependency injection.

Question: What are directives in angular?

Answer: Directives are one of the core features of Angular. They allow an Angular developer to write new, application-specific HTML syntax. In actual, directives are functions that are executed by the Angular compiler when the same finds them in the DOM. Directives are of three types: Attribute Directives, Component Directives and Structural Directives.

An Angular component isn’t more than a directive with a template. When we say that components are the building blocks of Angular applications, we’re actually saying that directives are the building blocks of Angular applications.

Question: What are lifecycle hooks in angular?

Answer: A component in Angular application has a life-cycle i.e. a number of different phases it goes right from its initiation to the end. We can hook into those different phases to get some pretty fine-grained control of our application. To do this we add some specific methods to our component class which gets called during each of these life-cycle phases, we call those methods Lifecycle hooks in angular. Here are the lifecycle hooks available in angular.

  1. ngOnChanges: This method is called whenever the value of the data-bound property changes.
  2. ngOnInit: This method gets fired or called in the initialization of the directive or component after the Angular first displays the data-bound properties that happen.
  3. ngDoCheck: This lifecycle hook is used for the detection and to act on changes that Angular can’t or won’t detect on its own.
  4. ngAfterContentInit: This is called in response after Angular projects external content into the component’s view.
  5. ngAfterContentChecked: This method is called in response after Angular checks the content projected into the component.
  6. ngAfterViewInit: This method is called after Angular initializes the component’s views and child views.
  7. ngAfterViewChecked: This is called in response after Angular checks the component’s views and child views.
  8. ngOnDestroy: This is the cleanup phase just before Angular destroys the directive/component.
  9. ngOnChange: This lifecycle is called before ngOnInit() and whenever one or more data-bound input properties change.

Question: What is the difference between constructor and ngOnInit?

Answer: Constructor is more like a Typescript thing then angular. TypeScript classes have a default method called constructor which is normally used for initialization purposes. Whereas the ngOnInit method is specific to Angular, especially used to define Angular bindings.

Even though the constructor gets called first, it is preferred to move all of your Angular bindings to ngOnInit method. ngOnInit will be executed When Angular did with the creation of component DOM.

The ngOnInit lifecycle hook Initialize the component after Angular first displays the data-bound properties and sets the component’s input properties.

export class App implements OnInit{
  constructor(){
     //called first time before the ngOnInit()
  }

  ngOnInit(){
     //called after the constructor and called  after the first ngOnChanges()
  }
}

Question: What is the difference between Angular and jQuery?

Answer: One of the biggest and most important differences between Angular and jQuery is that while the former is a JS frontend framework, the latter is a JS library. Despite this, there are some similarities between the two, such as both features DOM manipulation and provides support for animation. But there are also some features like Data Binding, support for restful API and form validation, in which Jquery lies behind.

Basically, jQuery is a great tool for you to manipulate and control DOM elements. If you only focus on DOM elements and no Data CRUD, like building a website not web application, jQuery is one of the top tools. But if your focus or goal is to build a full-fledged web application, Angular will always be a great choice.

Question: What is Interpolation in Angular?

Answer: Angular interpolation is used to display a component property in the respective view template with double curly braces syntax. Interpolation moves data in one direction from our component to the template.

It is represented by double curly braces({{}}). The text between the braces is often the name of a component property. Angular replace that name with the string value of the associated component property. Here is an example showing how to use interpolation in angular.

 <h3> {{title}} <img src="{{url}}" style="height:30px"> </h3> 

In the example above, we can see that the Angular evaluates the title and URL properties and fills in the blanks, first displaying a bold application title and then a URL.

Question: What is Angular Material?

Answer: Angular Material is a UI or User Interface library build for the angular framework. Angular Material Library helps in creating attractive, consistent, and fully functional web pages as well as web applications that are responsive in nature as well. It does so while following all the popular modern web design principles, including browser portability and graceful degradation.

Question: What is the difference between promise and observable?

Answer: An observable is essentially a stream (a stream of events, or data) and compared to a Promise, an Observable can be canceled. 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

Question: What is AOT (Ahead-Of-Time) Compilation in Angular?

Answer: Ahead of Time refers to a process in angular in which each angular apps gets compiled internally. The Angular compiler takes in the JS code, compiles it and then produces some JS code. This happens only once per occasion per user.

Question: How do you categorize data binding types in angular?

Answer: Binding types can be grouped into three categories distinguished by the direction of data flow which are as follows: – From the source-to-view, From view-to-source and from View-to-source-to-view which is also called as Two-Way Data Binding.

The possible binding syntax can be tabularized as below

Data direction Syntax Type
From the source-to-view(One-way) 1. {{expression}} 2. [target]=”expression” 3. bind-target=”expression” Interpolation, Property, Attribute, Class, Style
From view-to-source(One-way) 1. (target)=”statement” 2. on-target=”statement” Event
View-to-source-to-view(Two-way) 1. [(target)]=”expression” 2. bindon-target=”expression” Two-way

Question: Why is ngfor used in angular?

Answer: ngfor is used to loop through an array of items in the template and display each item in the list. Here is the example for the same.

 <li *ngFor="let user of users"> {{ user }} </li> 

Question: why is ngIf is used in Angular?

Answer: Sometimes in a web application, it is needed to app needs to display or view only some items which passed the given conditions. The Angular ngIf directive inserts or removes an element based on a truthy/falsy condition. Here is the example of ngIf in Angular.

<p *ngIf="user.age > 18">You are not eligible for student pass!</p>

It must be noted that Angular isn’t showing and hiding the message. It is adding and removing the paragraph element from the DOM. That improves performance, especially in the larger projects with many data bindings.

Question: What is SPA (Single Page Application) in Angular?

Answer: In Single page web application only a single page, which is index.HTML, is maintained although the URL keeps on changing. The single-page application (SPA) basically a web app whose all functionalities are framed on a single page where users can navigate different sections of the page by clicking on its dedicated links or buttons.

There is no need to refresh the complete page. All you need to do is to load or refresh the specific component. Also, Single page application also known as SPA is the best when it comes to code optimization as all the HTML, CSS and JS files are rendered on the same page.

Question: What is Transpiling in Angular?

Answer: Transpiling is the process by which all the typescript code used for Angular applications, gets internally transpiled into equivalent JavaScript.

Question: What is Angular CLI?

Answer: Angular CLI(Command Line Interface) is a command line interface to scaffold and build angular apps using node js style (commonJs) modules. You need to install using below npm command.

npm install @angular/cli@latest

Below are the list of few commands, which will come handy while creating angular projects

  1. Creating New Project: ng new
  2. Generating Components, Directives & Services: ng generate/g The different types of commands would be,
  3. ng generate class my-new-class: add a class to your application
  4. ng generate component my-new-component: add a component to your application
  5. ng generate directive my-new-directive: add a directive to your application
  6. ng generate enum my-new-enum: add an enum to your application
  7. ng generate module my-new-module: add a module to your application
  8. ng generate pipe my-new-pipe: add a pipe to your application
  9. ng generate service my-new-service: add a service to your application
  10. Running the Project: ng serve

Read Also: Learn about Angular CLI in details

Question: What is pipe in Angular?

Answer: A pipe takes in data as input and transforms it to a desired output. This is great for simple transformations on data but it can also be used in other unique ways.

For example, let us take a pipe to transform a component’s birthday property into a human-friendly date using date pipe.

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

@Component({
  selector: 'app-birthday',
  template: `<p>Birthday is {{ birthday | date }}</p>`
})
export class BirthdayComponent {
  birthday = new Date(1987, 6, 18); // June 18, 1987
}

Question: What are the different types of pipes available in Angular?

Answer: Angular has various inbuilt pipes which can be used to format the value of expression so that it can be displayed to the user. It is possible to add these pipes to the controllers, directives, services, or templates. Angular also provides support for creating custom pipes.

Pipes are used to organise the data in such a way so that it is displayed only when certain criteria are fulfilled. Pipes are added to the expressions using the pipe ‘|’ character. Various types of Angular Pipes or also called as Angular filters are enumerated as follows:

  1. currency – Formats a number to the currency format.
  2. date – Formats a data to some specific format.
  3. filter – Selects a subset of items from an array.
  4. json – Formats an object to a JSON string.
  5. limitTo – Limits an array or string into a specified number of characters or elements.
  6. lowercase – Formats a string to lowercase.
  7. number – Formats a number to a string.
  8. orderBy – Orders an array by an expression

Question: What is async pipe in Angular?

Answer: The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks. Here is an example of async pipe with a time observable that continuously updates the view for every 2 seconds with the current time.

@Component({
  selector: 'async-observable-pipe',
  template: `<div><code>observable|async</code>:
       Time: {{ time | async }}</div>`
})
export class AsyncObservablePipeComponent {
  time = new Observable(observer =>
    setInterval(() => observer.next(new Date().toString()), 2000)
  );
}

Question: What is a bootstrapping module in Angular?

Answer: Every application has at least one Angular module, the root module that you bootstrap to launch the application is called bootstrapping module. It is commonly known as AppModule. The default structure of AppModule generated by AngularCLI would be as follows.

/* JavaScript imports */
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

/* the AppModule class with the @NgModule decorator */
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Question: What are ngModule Decorator in angular?

Answer: The @NgModule decorator identifies AppModule as an NgModule class. @NgModule takes a metadata object that tells Angular how to compile and launch the application. There are various parameters which are passed in ngModule Decorator which are as follows

  1. declarations—this application’s lone component.
  2. imports—import BrowserModule to have browser-specific services such as DOM rendering, sanitization, and location.
  3. providers—the service providers.
  4. bootstrap—the root component that Angular creates and inserts into the index.html host web page.

Question: What are observables in Angular?

Answer: One of the most popular and useful features of the Angular is – Observables. Observables open up a continuous channel of communication in which multiple values of data can be emitted over time. From this we get a pattern of dealing with data by using array-like operations to parse, modify and maintain data.

Angular uses observables extensively – you’ll see them in the HTTP service and the event system. Observables are declarative which provide support for passing messages between publishers and subscribers in your application. They are mainly used for event handling, asynchronous programming, and handling multiple values. Here is an example showing how to make an Observable.

import { Observable } from 'rxjs';

const observable = new Observable(observer => {
  setTimeout(() => {
    observer.next('Hello from a Observable!');
  }, 2000);
});

Question: What is Subscribers in Angular?

Answer: Whenever an Observable instance begins publishing values, you need to subscribe to it to get values. The method by which you subscribe to an observable is known as subscribe() method.

You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications. Let’s take an example of creating and subscribing to a simple observable, with an observer that logs the received message to the console.

// Create simple observable that emits three values
const myObservable = of(1, 2, 3);

// Create observer object
const myObserver = {
  next: x => console.log('Observer got a next value: ' + x),
  error: err => console.error('Observer got an error: ' + err),
  complete: () => console.log('Observer got a complete notification'),
};

// Execute with the observer object
myObservable.subscribe(myObserver);
// Logs:
// Observer got a next value: 1
// Observer got a next value: 2
// Observer got a next value: 3
// Observer got a complete notification

Question: What is Observer in Angular?

Answer: Observer is an interface for a consumer of push-based notifications delivered by an Observable. It has below structure.

interface Observer<T> {
  closed?: boolean;
  next: (value: T) => void;
  error: (err: any) => void;
  complete: () => void;
}

A handler that implements the Observer interface for receiving observable notifications will be passed as a parameter for observable as below.

myObservable.subscribe(myObserver);

Note: If you don’t supply a handler for a notification type, the observer ignores notifications of that type.

Question: How to create Custom pipe in Angular?

Answer: You can create custom reusable pipes for the transformation of existing value. For example, let us create a custom pipe for finding file size based on an extension.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'customFileSizePipe'})
export class FileSizePipe implements PipeTransform {
  transform(size: number, extension: string = 'MB'): string {
    return (size / (1024 * 1024)).toFixed(2) + extension;
  }
}

Now you can use the above pipe in template expression as below

 template: `
    <h2>Find the size of a file</h2>
    <p>Size: {{288966 | customFileSizePipe: 'GB'}}</p>
  `

Question: What are parameterized pipe in Angular?

Answer: The parameterized pipe can be created by declaring the pipe name with a colon ( : ) and then the parameter value. If the pipe accepts multiple parameters, separate the values with colons. Let’s take a birthday example with a particular format(dd/mm/yyyy):

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

    @Component({
      selector: 'app-birthday',
      template: `<p>Birthday is {{ birthday | date:'dd/mm/yyyy'}}</p>` // 18/06/1987
    })
    export class BirthdayComponent {
      birthday = new Date(1987, 6, 18);
    }

Question: How to chain Pipe in angular?

Answer: Angular provides the functionality of chaining multiple pipes. You can chain pipes together in potentially useful combinations as per the needs. Let’s take a birthday property which uses date pipe(along with parameter) and uppercase pipes as below

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

        @Component({
          selector: 'app-birthday',
          template: `<p>Birthday is {{  birthday | date:'fullDate' | uppercase}} </p>` // THURSDAY, JUNE 18, 1987
        })
        export class BirthdayComponent {
          birthday = new Date(1987, 6, 18);
        }

Question: What is Pure and Impure pipe in angular?

Answer: There are two categories of pipes in angular: pure and impure pipe. Pipes are pure by default which means the value of pure property is true. You can make a pipe impure by setting its pure flag to false.

A pure pipe is only called when Angular detects a change in the value or the parameters passed to a pipe. For example, any changes to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).

An impure pipe is called for every change detection cycle no matter whether the value or parameters changes. i.e, An impure pipe is called often, as often as every keystroke or mouse-move.

Question: What is RxJS in Angular?

Answer: RxJS is a very popular library for composing asynchronous and callback-based code in a functional, reactive style using Observables. RxJS makes it easier to compose asynchronous or callback-based code.

RxJS provides an implementation of the Observable type, which is needed until the type becomes part of the language and until browsers support it. The library also provides utility functions for creating and working with observables.

Many APIs such as HttpClient produce and consume RxJS Observables and also uses operators for processing observables. For example, you can import observables and operators for using HttpClient as below

import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

Question: What is Angular Router?

Answer: The Angular Router is a feature provided in angular which enables navigation from one view to the next as users perform application tasks. Angular Router is a mechanism in which navigation happens from one view to the next as users perform application tasks. It borrows the concepts or model of browser’s application navigation.

It can pass optional parameters along to the supporting view component that help it decide what specific content to present. You can bind the router to links on a page and it will navigate to the appropriate application view when the user clicks a link.

Question: What is the purpose of base href tag in angular?

Answer: The routing application should add an element to the index.html as the first child in the tag inorder to indicate how to compose navigation URLs.

Angular adds base href in index.html to tell router how to compose navigation URLs. By default base URL is set as (/) or root. If app folder is the application root then you can set the href value as below

<base href="/">

Question: What are the router imports in Angular?

Answer: Angular Router is an optional service that presents a particular component view for a given URL. It is not part of the Angular core. It is in its own library package, @angular/router.

You can import what you need from it as you would from any other Angular package. For example, we import them in app module as below.

import { RouterModule, Routes } from '@angular/router';

Question: What is router outlet in angular?

Answer: The RouterOutlet is a directive from the router library and it acts as a placeholder that marks the spot in the template where the router should display the components for that outlet.

Router Outlet is used to load the different components dynamically based on the activated component or current route state. Router outlet is used like a component which is shown below.

<router-outlet></router-outlet>
<!-- Routed components go here -->

Question: What are router links?

Answer: The RouterLink is a directive on the anchor tags that give the router control over those elements. Since the navigation paths are fixed, you can assign string values to router-link directive as below.

<h1>Angular Router</h1>
<nav>
  <a routerLink="/todosList" >List of todos</a>
  <a routerLink="/completed" >Completed todos</a>
</nav>
<router-outlet></router-outlet>

Question: What are active router links in angular?

Answer: RouterLinkActive is a directive that toggles css classes for active RouterLink bindings based on the current RouterState. i.e, the Router will add CSS classes when this link is active and and remove when the link is inactive.

For example, you can add them to RouterLinks as below

<h1>Angular Router</h1>
<nav>
 <a routerLink="/todosList" routerLinkActive="active">List of todos</a>
 <a routerLink="/completed" routerLinkActive="active">Completed todos</a>
</nav>
<router-outlet></router-outlet>

Note: Active route links cascade down through each level of the route tree, so parent and child router links can be active at the same time.

Question: What is router state in angular?

Answer: RouterState is a tree of activated routes. Every node in this tree knows about the “consumed” URL segments, the extracted parameters, and the resolved data. You can access the current RouterState from anywhere in the application using the Router service and the routerState property.

@Component({templateUrl:'template.html'})
class MyComponent {
  constructor(router: Router) {
    const state: RouterState = router.routerState;
    const root: ActivatedRoute = state.root;
    const child = root.firstChild;
    const id: Observable<string> = child.params.map(p => p.id);
    //...
  }
}

Question: What is the purpose of Wildcard route in angular?

Answer: Wildcard route is used in the case in which, if the URL doesn’t match any predefined routes then it causes the router to throw an error and crash the app. A wildcard route has a path consisting of two asterisks to match every URL. For example, you can define PageNotFoundComponent for wildcard route as below.

{ path: '**', component: PageNotFoundComponent }

Question: What is activated route in angular?

Answer: ActivatedRoute contains the information about a route associated with a component loaded in an outlet. It can also be used to traverse the router state tree. The ActivatedRoute will be injected as a router service to access the information. Here is the example of the activated route and how to use it.

@Component({...})
class MyComponent {
  constructor(route: ActivatedRoute) {
    const id: Observable<string> = route.params.pipe(map(p => p.id));
    const url: Observable<string> = route.url.pipe(map(segments => segments.join('')));
    // route.data includes both `data` and `resolve`
    const user = route.data.pipe(map(d => d.user));
  }
}

Question: What is multicasting in angular?

Answer: Multi-casting is the practice of broadcasting to a list of multiple subscribers in a single execution. In simple words, Multicasting is the term used to describe the situation in which each notification emitted by a single observable is received by multiple observers. Let’s demonstrate the multi-casting feature with an example.

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({...})`:
multicasted.subscribe({
  next: (v) => console.log('observerA: ' + v)
});
multicasted.subscribe({
  next: (v) => console.log('observerB: ' + v)
});

// This is, under the hood, `s

So, this is all about The Best Angular Interview Questions. Thanks for reading and the new angular interview questions are constantly added on the list, so keep a eye on it also.

Leave a Comment