Top 30+ Angular Interview Questions and Answers

In this blog, I have prepared a set of important Angular interview questions and their answers which are very important from the point of the interview.

The Angular interview questions given below are based on version 8 and 9 of Angular.

Angular is outstanding amongst other programming languages in 2020. Created and maintained by Google, it assists software engineers with building adaptable and performant web applications.

This collection of Angular interview questions will surely be useful for your job interview, however before we get into that, let us rapidly recap about Angular.

1. What is Angular?

Angular is a well known powerful web application framework which helps to develop single page application. It is a Type Script based open source technology used to develop performance oriented web applications. To provide a better stability and highly optimized web application, Angular has released multiple versions time to time.
For more about Angular introduction, please visit this link – Angular Introduction

Below are the versions of Angular

Version Release Date LTS (Long term support)
11 Nov, 2020 Yes
10 Jun, 2020 Yes
9 Feb, 2020 Yes
8 May, 2019 Yes
7 Oct, 2018 No
6 May, 2018 No
5 Nov, 2017 No
4 Mar, 2017 No

2. What is TypeScript?

TypeScript is a typed super-set of Java Script that compiles the code into JavaScipt. In order to work with TypeScript, first you have to install the node package manager from npmjs.com Once npm installation is done, open command prompt and type below command.

npm install -g typescript – This command will install TypeScript globally to your system.

To check version tsc –version – This will show you the installed version of TypeScript. Learn TypeScript

3. Explain Lifecycle Hook in Angular

The list of processes that Angular experiences from start to end are called as lifecycle hook.
Below are the list of Lifecycle hook methods in Angular
  • ngOnChanges
  • ngOnInit
  • ngDoCheck
  • ngAfterContentInit
  • ngAfterContentChecked
  • ngAfterViewInit
  • ngAfterViewChecked
  • ngOnDestroy

4. Angular CLI Commands

Below are few Angular CLI commands that are useful while developing an Angular Application. To install Angular CLI

npm install -g @angular/cli

To get online help

ng help

To get detailed help of a command

ng [command name] --help

To get Angular version details

ng --version

For more list of Angular CLI commands, please visit this link – Angular Cli Commands

5. What are Components in an Angular Project?

Component is the basic building block of an Angular application. Any web page you see in Angular is a component. Any Angular project is the collection of multiple components. A component is a part of a module within an Angular project.

A component is mainly a collection of 4 files – .html, .ts, .scss, .spec.ts A single component is responsible for handling a single view.

An angular project must have at least one component. When creating a new project we have a component file named app.component (app.component.ts and app.component.html)

To add a new component within your Angular project, run below command – ng g c Whenever we create a new component, it is defined in its respective module file.

6. What is a Module?

The basis of any angular project is a Module. Simply, the Module is a collection of components. By default, in every Angular project, there is a Module file called root module (app.module.ts)

Multiple modules can be created within a single Angular application. Suppose that you are working on a project that is very big and complex.

In such a project or application, you will need more than one Module file, so that your application will be simple and well maintainable.

For eg – You can create a module for Customer, another module for Admin and so on. You can create components for your customer within the Customer module and components for the admin section within the Admin module. To add a new module within your project, run below command – ng g m

7. What is Directive in Angular?

It is one another important interview question. Directives in Angular extend the use of HTML elements by adding custom behavior. In this blog, we will see the use of directives in Angular. There are 3 types of directives in Angular –

  • Component Directives: Components are the most common directives among all. We can not create an Angular app without component directives. Naming conventions of a component in Angular app is .component.ts
  • Structural Directives: Structural Directives make changes in DOM by altering DOM elements. Structural directives in Angular starts with *
  • Attribute Directives: Attribute directives make changes in appearance and behavior of an element or component.

Visit this link to know more about Directives in Angular – Directives in Angular

8. Explain ngIf, ngSwicth, ngFor directives

ngIf, ngSwicth, ngFor are structural types of directives as these directives make changes in DOM by modifiying the DOM elements. Click Here to know more about Angular Directives.

9. What is Interpolation in Angular?

Interpolation is a way to bind a value in a component’s template. For eg – {{Property_Name}} In Component.ts file

export class TestComponent implements OnInit {
  message: any;
 
  constructor( ) { }

  ngOnInit() {
     this.message = 'Hello to Angular'
  }

In template file –

{{message}}

10. What is Event Binding in Angular ?

Event binding enables the template file to listen for keypress, mouseclick, touches etc.

 <button (click)="ShowAlert()">Show</button>
    Or you can use like this-
    <button on-click="ShowAlert()">Show</button>

11. What are Pipes? Use of Pipes in Angular with examples.

Pipes in Angular transform the data before it displays it to view. Angular offers built-in pipes and custom pipes as well. To apply pipe Angular uses | symbol before any pipe. Syntax to use pipe in Angular – {{| }} Few buil-in pipes are – lowercase, uppercase, date etc…

12. How to create Custom Pipes?

If your requirement is fullfilled with built-in pipes then use them else you may create custom pipes to fullfill business requirements. First we have to generate files to work with a custom pipe. To do this use below command ng g p Create a pipe with name add which will do addition for given value and parameter. To generate a custom pipe with name add, we will use the below command.

ng g p add

Once we have generated the custom pipe files, we will modify the code as per our requirements. Open add.pipe.ts file in editor and make changes in transform() method.

export class AddPipe implements PipeTransform {

  transform(value: number, args: any): any {
  
  if(args)
  {
  return value + args;
  }
  else return value;
  }
  }

Import this pipe in respective module –

import { AddPipe } from './pipe/add.pipe';

Add this pipe in decalaration as well in module file. Now use below line in your conmponent and run the project to see the outpout.
{{10 | add:5}}

13. Explain Routing in Angular

Routing means navigating from one page to another page in an application. While creating a new Angular project through CLI, it ask ‘Would you like to add Angular routing? (y/N)’ Once you select yes, it creates a app-routing.module.ts file in src-> app folder. We have to define all the routes in Routes in the routing module file. Routes is an array of route configuration.

const routes: Routes = [
  {
    path: 'demo1',
    component: Demo1Component
  },
  {
    path: 'add-product',
    component: AddProductsComponent
  },
];

For more details on Angular Routing, please visit our blog – Routing in Angular

14. What is Route Guard in Angular?

Route guards in an Angular application facilitates to block a particular route based on user authentication or on some extra permissions. Use below command to create a route guard –

ng g g /guard/userguard

Import the newly created route guard in your module file. and add the routeguard name in the providers array in the module file. Now, define the route with route guard in app-routing.module.ts file

{path:'dashboard',component:DashboardComponent,canActivate:[UserguardGuard]}

Above route says, DashboardComponent can only be displayed if canActivate method of Userguard returns true. In routeguard file, check the condition, if it is matches the specified condition then return true else navigate to access denied page and return false. For more details on route guard, please visit this link – Route Guard in Angular

15. What are differences between Template Driven Form and Reactive Form approach?

It is one of the important Angular interview questions.

In template-driven approach, Forms input and Forms validation logic goes into component’s html file only. Template-driven approach is fine for small or medium level projects.

In the Reactive Form approach the validation function is written in component class. And Angular calls this function whenever there is a change of value in the input control. Reactive Form Approach is the best practice if we are working on a large and complex Angular application. For more details about Template Driven Form and Reactive Form approach, please visit this link – Template-driven and Reactive Forms approach

16. What is FormControl and FormGroup?

ReactiveFormsModule provides a set of classes and directives which helps us to achieve many features to build Reactive forms, FormGroup and FormControl are one of them.
  • FormControl: All input fields defined in the HTML template are the instance of FormControl.
  • FormGroup: It is an instance of a set of FormControl is referred as FormGroup

For more details about FormControl and FormGroup, please visit this link – FormControl, FormGroup and FormBuilder

17. What is FormBuilder Service in Angular

FormBuilder service uses group() method which takes an object with control name as key. To use FormBuilder in an Angular project, first import FormBuilder from angular/forms as shown in the code snippet below.

import { FormBuilder } from '@angular/forms';
  
   addProductForm = this.formBuildr.group(
    {
      productName: [],
      productCategory: [],
      productDetails: [],
      productCost: []
    }
  );

For more details about FormBuilder Service, please visit this link – FormControl, FormGroup and FormBuilder

18. What is FormArray in Angular?

FormArray is the collection of FormControl, FormGroup or FormArray. To use FormArray in Angular application, you have to import it like this –

import { FormGroup, FormBuilder, FormArray } from '@angular/forms';
  productForm: FormGroup;
  products: FormArray;
addProductItem(): void {
  this.products = this.productForm.get('products') as FormArray;
}
    <div formArrayName="items"
         *ngFor="let p of productForm.get('products').controls; let i = index;">
        <div [formGroupName]="i">
            <input formControlName="pname" placeholder="Product name">
            <input formControlName="details" placeholder="Product details">
            <input formControlName="cost" placeholder="Cost">
        </div>
    </div>

19. What is HttpClient?

HttpClient is available in ‘@angular/common/http’ and it offers a way to communicate with an API. HttpClient uses XMLHttpRequest that supports all the latest browsers to communicate with an endpoint. HttpClient uses RxJS observables which allows the Angular app to handle asynchronous operations.
For more details about Http Client, please read below blogs –

20. What is Observable in Angular?

It is one of the most asked Angular interview question.

Observable is available with the RxJS library. Angular uses Observable to implement the asynchronous process. Observable gets executed when a consumer calls Subscribe() function.
For details about Observable, please check this blog – Angular CRUD example with .Net Web API

21. What is JIT Compilation?

JIT stands for Just-in-time compilation and it is the default compilation mode used by Angular. JIT compilation converts the HTML and TypeScript code into java script code at runtime.

JIT Compilation command –

ng build

ng serve

22. What is AOT Compilation?

AOT stands for Ahead-of-Time, AOT compilation converts HTML and Type script code into Java Script code at build time. This is the recommended compilation mode for production.

AOT compilation commands –

  ng build --aot 

  ng server --aot

23. Explain One-Way Binding and Two-Way Binding in Angular

What is One-Way Binding in Angular?

One way data binding will bind data from the component to the view (DOM) or from view to the component.

It is is unidirectional. You can just bind the data from component to the view or vice-versa.

There are various ways of data binding which utilize one-way data binding from component to view.

The following are the ways, which uses one way data binding in Angular.

  • Interpolation Binding
  • Attribute Binding
  • Property Binding
  • Style Binding
  • Class Binding

What is Two-Way Binding in Angular?

Two-way data binding in Angular will assist users exchange data from component to view and from view the component. It works in bi-directionally manner.

Two-way data binding can be accomplished with ngModel directive in Angular.

The below angular code shows the data binding (ngModel), which is fundamentally the mix of both the square brackets of property binding and parentheses of the event binding.

<input type=”text” [(ngModel)] = ‘value’ />

24. What are Decorators in Angular?

Decorators are utilized to attach metadata to program components, for example, class and properties. Metadata is utilized to determine insights regarding program entities. Decorators give special importance to program elements. Here we will take a gander at probably the most generally utilized Decorators in Angular 2 and above.

There are mainly 4 types of decorators available in Angular.

  • Class Decorators – Example @Component and @NgModule
  • Property Decorators – It is used for properties inside a class. Example – @Input and @Output
  • Method Decorators-  It is used for methods inside a class. Example – e.g. @HostListener
  • Parameter Decorators – It is used for parameters inside constructor of a class. Example – @Inject

25. What are Class Decorators in Angular?

Angular offers us multiple class decorators. Every decorator has its own role. They are the high level decorators that we use to express the goal for classes.

To make an Angular class as a component, we need to decorate the class with the @Component decorator.

In basic words, a class decorators tells the nature of that class implies this class is a module or component.

Simply add the decorators to the class and Angular will do the rest of the things.

Refer below code snippet for better understanding.

  @Component({
  selector: 'app-demo-component',
  templateUrl: 'demo-component.component.html',
  styleUrls: ['deom-component.component.scss']
})
export class ExampleComponent {
  constructor() {
    //This class is Component. Write your class code here
  }
}

@NgModule({
  imports: [],
  declarations: [],
})
export class ExampleModule {
  constructor() {
    //This class is a module. Write your class code here.
  }
}

26. Explain differences between Decorators and Annotations

Below are the differences between Decorators and Annotations –

Decorators –

  • It is used to attach metadata to a class in Angular.
  • It is used by TypeScript compiler.
  • By default Decorators are supported in Angular.

Annotations –

  • It reflects the library of metadata.
  • It is hard-coded feature.
  • It is used by Traceur compiler.

27. Explain differences between Promise and Observables

Below table depicts the differences between Promise and Observables in Angular.

Promise Observables
It emits a single value at a time. Observables have the capacity to emit more than one values at a single time.
Promise can not be cancelled. It can be cancelled using unsubscribe() method.
It doesn’t have any operations. It provides map for filter, forEach
It throws error to the child promises. It throws the error to the subscribers.

28. How to pass data from Parent component to Child component in Angular?

If parent component wants to send data to child component then we have to use @Input decorator in case child component wants to send data to parent component then we use @Output decorator.

A demonstration with code snippet is available on below link –

How to pass data from one component to another component in Angular?

29. What do you mean by Dirty Check in Angular Form?

To stop the validator from showing errors before the user gets an opportunity to modify the form data, you should check for either the dirty or touched states in a control.

At the point when the user changes the value in the watched field, the control is set as “dirty”.

At the point when the user focuses the form control, the control is set as “touched”.

It checks whether a value has changed that hasn’t yet been synchronized across the application.

         this.myForm.markAsDirty();
        this.myForm.markAllAsTouched();

30. Name some of the events in Angular.

Below are few events that we use frequently in Angular.
  • (click)
  • (submit)
  • (blur)
  • (focus)
  • (keyup)
  • (keypress)
  • (keydown)
  • (mousedown)
  • (mouseenter)

31. How to consume an API using HttpClient in Angular?

HttpClient in Angular is used to consume a service to perform CRUD (Create, Read, Update and Delete) operation.

HttpClient is available in ‘@angular/common/http’ and it offers a way to communicate with an API. HttpClient uses XMLHttpRequest that supports all the latest browsers to communicate with an endpoint.

HttpClient uses RxJS observables which allows the Angular app to handle asynchronous operations.

A demonstration with code snippet is available on below link –

How to consume API from Angular?

32. What’s new in Angular 11?

Angular 11 was released on Nov 11, 2020 and as per Angular official website the Long term support (LTS) ends on May 11, 2022.
The major changes in Angular 11 are given below –
  • TypeScript 4.0 support
  • Webpack 5 Support
  • Faster Build
  • Moving from TSLint to ESLint

33. What is Async pipe?

Async pipe in Angular is use to subscribe an observable or promise to return the latest value.

You can use Async pipe like this –

  <tr *ngFor="let prd of ProductList | async">
Read this - Angular CRUD example with .Net Web API
To know more about Angular 11 features, visit this blog – New Features in Angular 11
 

Hope these Angular interview questions and answers are helpful to you.

Please share this within your community and comment below in case you have any feedback.

Leave a Comment