Top 60+ AngularJS Interview Questions and Answers

For Freshers

1. What is AngularJS?

The AngularJS framework is a JavaScript framework for creating rich and extensible web applications. It runs on plain JavaScript and HTML, so it doesn’t require any additional dependencies. Single Page Applications are ideal for AngularJS (SPA). It’s primarily used to link JavaScript objects to HTML user interface elements.

Check out angularjs courses for free.

2. What is a Single Page Application (SPA)?

SPA is a concept in which, instead of loading pages from the server through postbacks, we build a single shell page or master page and load the webpages inside it.

3. Explain what a $scope is in AngularJS.

The application model is referenced by the $scope object. It’s an expression execution sense. Scopes are organised in a hierarchical system that mirrors the application’s DOM structure. Expressions can be monitored and events can be propagated using scopes. The model is represented by scopes, which are objects that refer to it. They serve as a connection between the controller and the view.

4. What are Directives in AngularJS?

Directives are DOM element markers (such as an attribute, element name, comment, or CSS class) that tell AngularJS’ HTML compiler ($compile) to apply a particular behaviour to the DOM element (e.g. through event listeners) or even transform the DOM element and its children.

5. What is the difference between ng-show/ng-hide and ng-if?

If the specified condition is not met, ng-if does not render the portion of the DOM element with which it is connected, while ng-show/ng-hide renders the DOM element but sets its CSS property of display to hidden/visible if the specified condition is not met.

6. How do you establish two-way data binding in Angular?

The ngModel directive incorporates the input and output binding into a single notation. For example: <input [(ngModel)]=”name” > {{name}}

7. What are the different types of data bindings in AngularJS?

Both one-way and two-way binding are supported by AngularJS. If we modify the data model in one-way binding, there will be no dynamic change in the view, but in two-way binding, there will be a dynamic change whenever the data model is changed.

8. Explain string interpolation.

The double curly braces {{ }} represent data from a variable when used with an HTML tag. For instance, an HTML page containing {{variableName}}, where variableName refers to the value in the component. String interpolation is the term for this whole concept.

9. What are pipes (or filters in AngularJS)?

The primary function of filters is to adjust data so that it can be combined into an expression or directive using the pipe character (|). The value of an expression is formatted by a filter for presentation to the user. Pipes are used to modify the template’s output; the string is resized and displayed in the template. This can result in a shift in the date format.

10. What is the difference between ng-class and ng-style?

CSS class loading is possible in ng-class, while CSS style can be set in ng-style.

11. How do you make HTTP GET and POST calls in AngularJS?

To make HTTP calls, we must use Angular’s $http service. At least three things are needed by the $http service API: First, the method “POST” or “GET.” Second, the URL of the resource. Finally, a success function that will be called upon receiving a response.

12. What are services in AngularJS?

Dependency injection is made easier with the aid of a service. An AngularJS service allows business logic to be developed independently of the View logic that will be used for it. Services are one-of-a-kind components. A single instance of the service would be used by all components of the application (into which the service is injected).

13. How do you share data between controllers?

Create an AngularJS service that will store and inject the data into the controllers. Other options include using events, using $parent, nextSibling, etc., or adding data to $rootScope (not a good practice).

14. What is the difference between a Factory and a Service in AngularJS?

A Service creates a new global instance of an object that is injected. It’s best used for shared functions like loggers or error handlers. A Factory does not create an instance; it passes a method reference that the user must call to get object instances. It’s useful when you need to create different types of objects based on different scenarios.

15. What is the purpose of the Angular Router?

When we need the path to an element, we’ll use the router. Syntax: this.router.navigate ([‘/ component name']);

16. What is a Router Outlet and what does it do?

Router Outlet is a method for grouping elements that replaces templates. To put it another way, it represents or includes elements in a template at a particular location.

[routerLink] is a router command that can be used on elements to navigate to a new path.

18. What do HTTP method calls in modern Angular return?

Calls to HTTP methods in Angular return an observable rather than a promise.

19. Which method is used to listen for a response from an HTTP request?

In modern Angular, HTTP methods (like get(), post(), etc.) in the HttpClient service return an RxJS Observable. To receive the data or handle any potential errors, you must subscribe to this observable using the .subscribe() method.

Example:


this.http.get('/api/users').subscribe(
  data => {
    // This function runs on a successful response
    console.log(data);
  },
  error => {
    // This function runs if an error occurs
    console.error('An error occurred:', error);
  }
);

20. What is a component in modern Angular?

In Angular, a component is a class that is used to create building blocks.

21. How are the $ and $$ prefixes used in AngularJS?

The $$ variable is used as a private variable to avoid unintended code collisions. The $ prefix may be used to denote angular core functionality (like a variable, parameter, property or method).

22. Should you use jQuery with AngularJS? Why or why not?

It is a bad practice. AngularJS uses a declarative approach to DOM manipulation where you declare what you want, and AngularJS handles it. jQuery uses an imperative approach where the programmer must articulate the individual steps.

23. How do you specify that a scope variable in AngularJS should have one-time binding?

By using the prefix :: in front of it.

24. Explain the difference between sessionStorage, localStorage, and cookies.

  • SessionStorage: Data is saved for a specific session and is lost when the browser tab is closed. Max size is 5MB.
  • LocalStorage: Data has no expiration date and is only cleared by JavaScript or clearing the browser cache. The capacity is higher than sessionStorage.
  • Cookies: Saves data that must be sent back to the server. Expiration depends on the cookie settings. Max size is 4KB.

25. Can AngularJS be described as an MVC framework?

Yes.

26. What is the safe navigation operator (?) and what problem does it solve?

We should use ? in Angular to stop any unnecessarily erroneous file not found errors. For example, if we have contact details but didn’t provide a picture URL, using [src]=contact?.photoURL will prevent a 404 error.

27. What is the Angular CLI and what is the command to generate a new component?

The Angular generator allows us to generate components from the terminal. The command is ng generate component component-name.

28. What is Dependency Injection?

When a feature is dependent on another, dependency injection is the mechanism by which that dependency is provided to the feature. Services are a primary example of how dependency injection is used.

29. How do you check for validation errors on a form field?

You use code like !frm1.CustomerName.$valid to check a particular field.

30. Compare AngularJS and React.js at a high level.

  • Angularjs: A TypeScript-based framework launched by Google, used for Single Page Application (SPA) projects.
  • Reactjs: A JavaScript library for creating user interfaces, released by Facebook. React components can be used on several websites, but it is not inherently a full SPA framework.
Texas McCombs, UT Austin

Full Stack Development Course By UT Austin

Become a full stack developer with UT Austin's 28-week program. Learn full stack development with React, Node, SQL & MongoDB.

250+ hours
32 Projects
Start Learning Full Stack

For Experienced Developers

31. What is the difference between a component and a directive in modern Angular?

Components have their own HTML and Style (View), whereas a directive is simply a behaviour that extends the component’s elements.

32. What are the different ways components can communicate with one another?

Passing the state of one variable to another, and passing a value from a parent variable to a service.

33. Explain the differences between NgForm, FormGroup, and FormControl for building forms.

These are core building blocks for forms in Angular.

  • FormControl: Represents a single, individual form control, like an <input> or <select>. It tracks the value, validation status (valid, invalid, pending), and user interaction state (dirty, pristine, touched) of that one element.
  • FormGroup: A collection that groups multiple FormControls together. It tracks the combined status and value of its child controls. For example, a user registration form could be a FormGroup containing FormControls for a username, email, and password. The FormGroup is valid only if all of its child controls are valid.
  • NgForm: This is a directive specific to Template-Driven Forms. When you add a <form> tag to your component’s template and import the FormsModule, Angular automatically creates an NgForm directive. It wraps a FormGroup instance, collecting all the controls within the form that have an ngModel directive, and allows you to track the form’s overall state directly in the template.

34. What are the benefits of using the FormBuilder service for reactive forms?

FormBuilder speeds up the development of FormControl, FormGroup, and FormArray instances. It cuts down on the amount of boilerplate code required to create complex forms.

35. What is an async pipe and how does it help prevent memory leaks?

The async pipe subscribes to an Observable or Promise and returns its most recent value. When a new value is emitted, it marks the component to be checked for changes. It prevents memory leaks because the async pipe automatically unsubscribes when the component is destroyed.

36. What is the difference between a pure and an impure pipe?

A pure pipe is called by Angular only when it detects a change in the value or the parameters passed to the pipe. The provided text does not define an impure pipe.

37. What are the RxJS operators switchMap, concatMap, and mergeMap, and when would you use each?

  • switchMap: When a new mapped observable arrives, switchMap will unsubscribe from the previous one.
  • concatMap: Queues each new Observable and subscribes to it only after the previous one has completed.
  • mergeMap: Subscribes to every new observable that the map returns without unsubscribing from previous ones.

38. Explain the difference between scan() and reduce() in RxJS.

  • Scan: Sequentially applies a function to each value emitted by an Observable and emits each intermediate value.
  • Reduce: Sequentially applies a function to each value emitted by an Observable and emits only the final value after the source observable completes.

39. What is an HTTP Interceptor and what are its common use cases?

An interceptor is code that can manage bugs, authentication, or middleware in all HTTP requests and responses that pass through it.

40. Where should DOM manipulation logic be implemented in an AngularJS application?

In the directives. DOM Manipulation can only be done in directives, not in controllers, services, or anywhere else.

41. How would you programmatically modify a directive’s template before it is compiled?

The compile function will be used. The compile function gives you access to the directive’s template before transclusion and template transformation, enabling you to make adjustments to DOM elements safely.

42. What is a Directive Definition Object (DDO) in AngularJS?

The DDO is an object that is used to create custom directives. It contains properties like priority, template, templateUrl, restrict, scope, controller, link, and compile.

43. Explain how $scope.$apply() and $scope.$digest() work in the AngularJS digest cycle.

$scope.$apply() will re-evaluate all declared ng-models and apply the update to those that have changed. It causes the Angular engine to operate on all watched variables and external variables and apply changes to their values. The provided text does not explain $scope.$digest().

44. How do you cancel a $timeout, clear an $interval, and disable a $watch()?

  • To reset a $timeout or $interval, assign its result to a variable and then use the .cancel() function on that variable.
  • To disable a $watch(), save the deregistration function it returns into a variable, and then call that function to clean it up.

45. What are TypeScript decorators and how are they used in Angular (e.g., @Component, @Injectable)?

Decorators are enabled by a highlighted @ symbol, and a class, parameter, method, or property is generated. They are a future JavaScript feature already in use by Angular and TypeScript.

46. What is the singleton pattern and how does it relate to Angular services?

It is a pattern that prevents a class from being instantiated more than once. If an object already exists, the singleton pattern allows you to reuse it. In Angular, this pattern can be found in dependency injection and services.

47. How would you implement a global error handling strategy in an Angular application?

In modern Angular, you implement the ErrorHandler interface.

1. Create a Custom Handler Class: Create a new TypeScript class that implements ErrorHandler. This class must have a handleError(error: any) method.


import { ErrorHandler, Injectable } from '@angular/core';

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  handleError(error: any): void {
    // Your custom error handling logic goes here
    console.error('An error occurred:', error);
    // e.g., send the error to a logging service
  }
}

2. Provide the Handler: In your root AppModule, register this class in the providers array, telling Angular to use your custom handler instead of the default one.


providers: [{ provide: ErrorHandler, useClass: GlobalErrorHandler }]

48. What does the concept of a “lean component” mean to you?

We use the lean component solely to display data.

49. How do you create a custom directive in AngularJS?

You must use the directive function to register a custom directive with an Angular application. When calling the function, you must define the feature that will provide the rationale for that directive.

50. What are the four types of directive restrictions (E, A, C, M) in AngularJS?

  • E: Element directives
  • A: Attribute directives
  • C: CSS class directives
  • M: Comment directives

51. When creating a custom directive, when should you prefer restricting it to an element versus an attribute?

Use an element when building a component that is in charge of the template. Use an attribute when you’re adding new features to an existing element.

52. What is the concept of content projection in modern Angular (<ng-content>)?

Content projection is a pattern that allows you to make components more reusable by passing content from a parent component into a child component’s template. The child component defines a placeholder using the <ng-content></ng-content> element. When the parent component uses the child component, any HTML or components placed between the child’s selector tags (<app-child>...</app-child>) will be rendered inside the child’s template where <ng-content> is located. This is ideal for creating generic wrappers like cards, dialogs, or layout components.

53. What makes the angular.copy() method different from a standard variable assignment?

It duplicates the variable in a deep way. A deep copy does not share the same memory address as the original variable. A standard assignment creates a “shallow copy,” where both variables point to the same memory location.

54. How do you work with promises in an AngularJS service using the $q service?

Inject the $q dependency into the service. Inside a service method, create a deferred object using $q.defer(). After an async operation (like an API call) completes, you call deferred.resolve(data). The method then returns deferred.promise.

55. What is the role of transclusion in AngularJS directives?

Transclusion was the AngularJS (v1.x) feature that is equivalent to content projection in modern Angular. By setting transclude: true in a directive’s definition, you could capture the content from inside the directive’s element and then place it into a specific location within the directive’s own template using the ng-transclude directive.

56. How would you implement application-wide exception handling in your Angular app?

$exceptionHandler is an Angular built-in error handler that can be overridden by creating a factory for it. Inside, you can return a function that takes exception and cause as arguments to log them or send them to an error service.

57. What are some strategies for optimizing the performance of an Angular application?

  • Lazy Loading: Split your application into feature modules and load them on demand as the user navigates to them. This dramatically reduces the initial bundle size and improves load time.
  • OnPush Change Detection: For components whose inputs are immutable, change their detection strategy to OnPush. This tells Angular to only check the component for changes when its inputs change, an event is fired from it, or an observable it’s subscribed to (via the async pipe) emits.
  • AOT Compilation: Use Ahead-of-Time (AOT) compilation for production builds. This compiles templates during the build process, leading to faster rendering in the browser and a smaller application size.
  • trackBy for *ngFor: When rendering lists with *ngFor, provide a trackBy function. This helps Angular identify which items in the list have changed, preventing it from re-rendering the entire DOM for the list on every data update.

58. What is Change Detection in Angular, and what are the different strategies (OnPush vs. Default)?

Change Detection is the process by which Angular updates the view (the DOM) when the application’s data changes.

  • Default Strategy: In this mode, Angular checks every component in the component tree for changes whenever an event occurs (e.g., a user click, an HTTP response, a timer). This is thorough but can be inefficient in large applications.
  • OnPush Strategy: This is an optimization strategy. When a component is set to OnPush, Angular will only run its change detection (and check its template bindings) when one of the following occurs:
    • A new reference is passed to one of its @Input() properties.
    • An event (like a (click)) originates from the component or one of its children.
    • It is explicitly marked for checking (e.g., via ChangeDetectorRef.markForCheck()).
    • An observable it is subscribed to in its template via the async pipe emits a new value.

59. What are the key architectural differences between AngularJS and modern Angular (Angular 2+)?

  • Architecture: AngularJS was based on MVC (Model-View-Controller). Modern Angular is entirely component-based. The application is a tree of components, each encapsulating its own view, style, and logic.
  • Language: AngularJS was a JavaScript framework. Modern Angular is built with TypeScript, which provides static typing, improved tooling, and better scalability.
  • Performance: Modern Angular is significantly faster due to a more efficient change detection system, Ahead-of-Time (AOT) compilation, and a redesigned architecture.
  • Tooling: Modern Angular is supported by the Angular CLI, a powerful command-line tool that standardizes project creation, code generation, builds, and updates, which was absent in the AngularJS ecosystem.

60. What was the purpose of the bindToController property in an AngularJS directive?

In AngularJS, bindToController was a property in the Directive Definition Object (DDO) used to simplify component-like directives. When you created a directive with an isolated scope and a controller, you would typically have to access the scope properties via $scope. Setting bindToController: true made it so that properties defined in the isolated scope were automatically bound directly to the controller’s instance (this), making the controller code cleaner and more similar to a modern component class.

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.
Scroll to Top