Advanced Angular Interview Questions

Tushar Ghosh
8 min readApr 20, 2024

--

Photo by Ferenc Almasi on Unsplash

In 2024, recession and lay off still is on going. Many developers are looking for a job. This is not a ideal situation you will get experience from your first and second interview and crack the third interview. Right now its difficult to get a interview call. You will prepared yourself so that you can crack your first interview. Last 3 months, I got three interviews. I cracked all of them.

For Angular preparation, I noted down about angular in google drive. I am sharing it in article in medium to help others to prepare for Angular interview. I tried to connect some questions to design patterns and tried to discuss scenario based questions.

What kind of steps you will take to improve the Angular application?

  • Remove unnecessary library and code
  • Use trackBy in ngFor loops
  • Caching the static file to improve the performance
  • ng-container is a structural directive that doesn't create any additional DOM elements. ng-container is to provide a grouping mechanism for applying structural directives like ngIf, ngFor, and ngSwitch without introducing unnecessary HTML elements.
  • Compressed the image size in application
  • Implement lazy loading for modules. This helps in loading only the necessary parts of your application when they are needed, reducing the initial load time
  • Use pagination or infinite scrolling to improve the data load in the page.
  • Integrate webpack-bundle-analyzer to investigate the component size and third party library size
  • OnPush change detection strategy is also used for improving the Angular performance improvement. Angular doesn’t need to traverse the entire component tree structure for detecting individual changes on properties. We can re render the component on demand in this strategy.

How many way we can share data between component?

  1. Input/Output Binding: Parent components can pass data to child components through input properties (@Input decorator) and receive data from child components through output properties (@Output decorator).
  2. ViewChild/ContentChild: Parent components can access child components and their properties using ViewChild and ContentChild decorators.
  3. Services: Shared data can be managed and accessed using Angular services. Components can inject the same service instance and use it to share data.
  4. State Management: NgRx can be used for managing application state and sharing data between components using a centralized store.

Is it possible to call an API in the constructor of an Angular component instead of using the ngOnInit lifecycle hook?

While it is technically possible to call an API from the Angular constructor, it’s not considered a best practice. The constructor is invoked when the component class is initialized, before Angular has fully initialized certain features like dependency injection or input properties. This means that calling an API before these features are fully available may lead to unexpected behavior or errors.

What are some of the differences between a standard Angular component and a standalone component?

  • Standard components must be included in an NgModule to be used within an Angular application. Standalone components do not require this and can be used independently without being included in an NgModule.
  • Standard components require imports for Angular or third-party functionality to be declared in the NgModule. For instance, *ngFor directive usage necessitates importing CommonModule from @angular/common in the NgModule. In contrast, standalone components can directly import dependencies within their own files.

How to prevent cross-site scripting (XSS) in Angular

  • Interpolation and Property Binding: Angular’s built-in mechanisms for data binding, such as interpolation ({{ }}) and property binding ([ ]), automatically sanitize user input, making it safe to render in the browser. Always use these mechanisms when rendering dynamic content to prevent XSS.
  • Sanitize User Input: If you’re dealing with dynamic content that may contain HTML, CSS, or JavaScript, use Angular’s built-in DomSanitizer service to sanitize the input before rendering it in the DOM.
mport { DomSanitizer } from '@angular/platform-browser';

constructor(private sanitizer: DomSanitizer) {}

// Sanitize user input
sanitizedHtml = this.sanitizer.sanitize(SecurityContext.HTML, userInput);
  • Angular Templates Safely: Avoid using innerHTML or outerHTML to dynamically generate HTML content. Instead, utilize Angular's template syntax to safely render dynamic content.

What are Host Binding and Host Listening in Angular?

In Angular, @HostBinding and @HostListener decorators are used to interact with the host element of a directive or component.

@HostBinding: The @HostBinding decorator is used to bind a property of the host element. It allows you to set a property on the host element based on a property of the directive or component.

import { Directive, HostBinding } from '@angular/core';

@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@HostBinding('style.backgroundColor')
backgroundColor: string = 'yellow';
}

@HostListener: The @HostListener decorator is used to listen for events on the host element. It allows you to define a method that will be called when a specific event occurs on the host element

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

@Directive({
selector: '[appClickLogger]'
})
export class ClickLoggerDirective {

@HostListener('click', ['$event'])
onClick(event: Event): void {
console.log('Host element clicked!', event);
}

}

I was asked “You have one input field and, after submission, you receive a response with the length of the entered input. How would you implement this in Angular?”

This is a simple question, and I know you can finish it in a few minutes. However, the interview’s intention is to understand how deeply you know Angular and what kind of steps you would take to complete this task.

When you face such kind of question try to cover as much as possible like Security, Error handing, Testing, State management, Form validation, API call, Interceptor.

Here is some basic ideas

  • Basic Implementation: Try to discuss Reactive Forms and Template-driven Forms. Its pros and cons. Finally choose one of them. I will go reactive form because of extensive validation, dynamic controls and better for testing.
  • Security: I am very much concern about security. I will use Dom Sanitizer to sanitize input to prevent cross-site scripting (XSS).
  • Error Handling: Angular provide ErrorHandlerinterface to handle the global error. I will use that to handle error in the Angular application. I will also use HttpClientInterceptor to intercept HTTP requests and handle errors returned by the server.
  • Testing: Testing ensures that your application functions correctly and meets the specified requirements. I will write unit testing and e2e testing using Karma and jasmine to make the application more stable.
  • State Management: I can manage state in componet level, service lever or global state like Ngrx. For this case, I will go with component level state access.
  • API Call: Angular provides HttpClient module that is used to send HTTP requests and receive responses from a server. Angular 2 and 4, they provided Http module from the Angular 5, they have made it HttpClient module. In here, I can easily manage error, even I can modified response date using Rxjs operator. For this problem, I can use both get and post call. But I will go post call because post is more secured.
  • Interceptor: I can use HTTP interceptors to intercept outgoing requests and incoming responses. For example I can use interceptor to add token in header.
  • Logging service: Log errors to a centralized logging service or platform for monitoring and debugging purposes.

There is no right wrong answer this type of question. This is the sample points that will help you to prepare yourself.

Tell me about Angular Lifecycle Hooks

There is 90% chance to face this question. The fun fact is that from amateur to advanced developer everybody knows the answer. The important part is how you delivery the answer make a difference from amateur. I always try to connect with my previous work experience.

Here is my answer:

This is a important question. There are 8 life cycle hooks in Angular. I have heavily used ngOnInit and ngOnDestroy in my previous work environment. ngOnInit is called when component initialize. It is called once. Mostly, I used for variable initialize and API call. ngOnDestroy is called before detroying the component. I heavily used for unsubscribe the subscription to prevent the memory leak.

Several times I have used ngOnChanges, ngAfterContentInit, ngAfterViewInit in my career. ngOnChanges method is called once on component’s creation and then every time changes are detected in one of the component’s input properties. It receives a SimpleChanges object as a parameter. ngAfterViewInit is called after the component view and its child views has been initialized. ngAfterContentInit is called after components external content (or from parent ) has been initialized.

There are other hooks like ngDoCheck, ngAfterContentChecked, ngAfterViewChecked, I did not use them too much.

What is Dependency Injection?

Whenever you have chance try to connect with design pattern. Try to add extra information in your answer that makes you are senior or experienced developer.

Here is my answer:

Dependency Injection (DI) is a design pattern. DI is heavily used in Angular. DI is a design pattern that aims to manage component dependencies by injecting them from external sources rather than creating them within the component itself. It is use to improved testability, make Components loose coupling.

By default, Angular’s DI system creates singleton instances of services and shares them throughout the application. In AngularJs, function params are used for DI, From Angular 2, constructor param is used for DI.

How much experience do you have with Angular?

I faced this question several times. I never answered this question like 7 years. I tried to make it informative to get the interviewer attention.

Here is my answer:

I started to work with Angular from Angular 2. Its from 2017. Angular 2 was released in September 2016. After that Angular team started to release new version in every 6 months. In Angular 5, they introduced httpClient. Angular 8 they introduce Ivy engine to make bundle size small. Ivy engine make it default in Angular 9. Then Angular 15, they introduce standalone component. Angular 17, They make it default. Angular 17, they have introduced Built-in control flow, Deferrable views, Angular Signals.

In a scenario where there are different design requirements for European and USA clients, with 70% of the design and components are being common. European and USA have separated server. They are deploying separately. How would you handle this situation?

We can solve it different way. We can use if else to handle the scenario for USA and European.

My suggestions are to use separate env files. For USA, we will have environment.usa.ts for European, we will have environment.european.ts . When we build the angular application for production we will select the environment name during build time.

ng build --prod --configuration=usa

or

ng build --prod --configuration=european

We will deploy the build files to corresponding server.

Here is some common questions that you should prepare yourself before interview

  • What is Angular, and why does Angular use TypeScript?
  • What is Angular Material?
  • What is a directive, and what are the types of directives
  • What are the building blocks of Angular?
  • What is Dependency Injection (DI)
  • What is data binding, and how many ways can it be implemented?
  • Could you explain the various types of filters in Angular.
  • What is ViewEncapsulation, and how many ways can it be implemented in Angular?
  • Why prioritize TypeScript over JavaScript in Angular?
  • What do you understand By RouterOutlet and RouterLink
  • What happens when you use the script tag within a template?
  • What is ViewChild and you will want to use {static: false}
  • How many ways can we share data between components?
  • Angular Lifecycle Hooks
  • What is AOT compilation? What are the advantages of AOT?
  • What is “sourceMap”: true in angular
  • What is RxJS?
  • Promise vs Obserable
  • What are Template and Reactive forms?
  • What are Forroot and childroot in Angular?
  • How to handle multiple http requests in Angular?
  • Map vs mergeMap vs switchMap vs concatMap
  • What are class decorators?
  • What is the Component Decorator in Angular?
  • Bundle Analysis
  • When to Use Put and Patch?
  • What is purpose of the Angular.json
  • Angular 17 new features:
  • What are some of the differences between a standard Angular component and a standalone component?
  • What is bootstrapModule in Angular?
  • Angular testing framework?
  • pre-fetch your data by using Resolvers
  • Guard in angular
  • Host binding and Host listening
  • Polyfill in Angular
  • Router outlet in angular
  • Can we use multiple router outlet
  • Can i write a component without constructor
  • Pure pipe vs Impure pipe
  • Formbuilder vs Formgroup in angular
  • View encapsulation in angular

In conclusion, I tried to describe my answer that will help you to prepare your answer. Good luck.

--

--

Tushar Ghosh
Tushar Ghosh

Written by Tushar Ghosh

MEAN | JavaScript | Node.js | React| Angular | Frontend

Responses (7)