Angular Interview Questions and Answers

Angular Interview Questions and Answers - EncodingCompiler

Quick answer

Angular is Google’s open-source TypeScript framework for building single-page web applications, and AngularJS (version 1.x) is the older JavaScript framework it replaced, which reached end of support at the end of 2021. Angular interviews start with components, templates, data binding, directives, pipes, services and dependency injection, then move to signals, change detection (zoneless and OnPush), RxJS, lazy loading, forms and performance.

Angular is one of the most widely used frameworks for large, long-lived web applications, especially in enterprise teams, and Angular interview questions follow a predictable path. Interviewers start with the building blocks (components, templates and data binding) and then test whether you understand how modern Angular actually works: signals, zoneless change detection, standalone components and the new template control flow.

These Angular interview questions are written for current Angular (v22, released June 2026). Many companies still maintain older AngularJS apps, so there is also a short section on AngularJS interview questions at the end. For the styling side of front-end interviews, see our CSS interview questions, and for the network layer behind HttpClient, see our HTTP interview questions.

Angular Interview Questions and Answers for Freshers

1. What is Angular?

Angular is an open-source, TypeScript-based framework from Google for building single-page applications (SPAs). It is a complete platform rather than just a view library: it includes components and templates, dependency injection, a router, forms, an HTTP client, testing utilities and a command-line tool (the Angular CLI). Angular releases a new major version roughly every six months, and each major version is supported for 18 months.

2. What is the difference between AngularJS and Angular?

They are two different frameworks that share a name. AngularJS was released in 2010; Angular (originally called Angular 2) was a complete rewrite released in 2016. Code from one does not run in the other without migration.

AngularJS (1.x) Angular (2+)
Language JavaScript TypeScript
Architecture Controllers and $scope (MVC style) Components and services
Change detection Digest cycle with watchers Signals, zoneless by default
Compilation In the browser at runtime Ahead of time (AOT) at build
Tooling Manual setup Angular CLI
Support Ended December 31, 2021 Actively developed

3. What is a component?

A component is the main building block of an Angular app. It is a TypeScript class marked with the @Component decorator, which links the class to an HTML template and its styles. The class holds the state and behavior; the template describes what the user sees.

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

@Component({
  selector: 'app-counter',
  templateUrl: './counter.html',
  styleUrl: './counter.css'
})
export class Counter {
  count = signal(0);

  increment() {
    this.count.update(c => c + 1);
  }
}
<!-- counter.html -->
<button (click)="increment()">Clicked {{ count() }} times</button>

You use the component anywhere by its selector: <app-counter />.

4. What are standalone components?

Standalone components declare their own dependencies in an imports array instead of being declared in an NgModule. Since Angular 19 every component, directive and pipe is standalone by default, so new apps usually have no NgModules at all. An app starts with bootstrapApplication(App, appConfig), and app-wide providers such as the router and HttpClient go in appConfig. NgModules still work, which matters when you maintain older code.

5. What are templates and interpolation?

A template is the HTML that defines a component’s view, extended with Angular syntax for bindings, events and control flow. Interpolation, written with double curly braces, inserts a value into the page as text: {{ user.name }} or {{ count() }}. The expression inside is evaluated against the component and re-rendered when the data changes. Template expressions should be fast and free of side effects, because Angular may evaluate them many times.

6. What are the types of data binding in Angular?

  • Interpolation (component to view): {{ title }}
  • Property binding (component to view): [disabled]="isSaving()", plus attribute, class and style bindings such as [class.active]="isActive"
  • Event binding (view to component): (click)="save()"
  • Two-way binding (both directions): [(ngModel)]="name" in forms, or [(value)] with a model() input on your own components

Two-way binding is just property binding plus event binding combined, which is why the syntax looks like a “banana in a box”: [( )].

Angular interview questions and answers: Angular Data Binding Types
Angular Data Binding Types (quick reference)

7. What are directives, and what types are there?

Directives are classes that add behavior to elements in a template. There are three kinds:

  • Components: directives with their own template.
  • Attribute directives: change the appearance or behavior of an element, for example ngClass, ngStyle or a custom appHighlight.
  • Structural directives: add or remove elements, such as the older *ngIf and *ngFor.

Since Angular 17, built-in control flow blocks replace most structural directives. They are faster, need no imports, and @for requires a track expression so Angular can reuse DOM elements efficiently:

@if (user(); as u) {
  <p>Welcome, {{ u.name }}</p>
} @else {
  <p>Please sign in</p>
}

<ul>
  @for (item of items(); track item.id) {
    <li>{{ item.name }}</li>
  } @empty {
    <li>No items yet</li>
  }
</ul>

8. What are pipes?

Pipes transform a value for display in a template without changing the underlying data, using the pipe character: {{ price | currency:'INR' }} or {{ createdAt | date:'mediumDate' }}. Built-in pipes include date, currency, number, percent, uppercase, lowercase, json, slice and async. AngularJS called these filters. You can write your own:

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

@Pipe({ name: 'truncate' })
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit = 20): string {
    return value.length > limit ? value.slice(0, limit) + '...' : value;
  }
}

Pipes are pure by default: Angular only re-runs them when the input value or reference changes, which makes them cheap. An impure pipe (pure: false) runs on every change detection pass and should be avoided for heavy work.

9. What is a service, and how does dependency injection work?

A service is a class that holds logic or data shared across components, such as API calls, authentication or a shopping cart. Angular’s dependency injection (DI) system creates services and hands them to the classes that need them, so components never create their dependencies with new.

@Injectable({ providedIn: 'root' })
export class CartService {
  private items = signal<Product[]>([]);
  readonly count = computed(() => this.items().length);

  add(product: Product) {
    this.items.update(list => [...list, product]);
  }
}

@Component({ /* ... */ })
export class Header {
  private cart = inject(CartService);
}

providedIn: 'root' makes one app-wide instance that is tree-shaken away if nothing uses it. The inject() function is now the preferred style over constructor parameters. Angular 22 also added a @Service decorator as a shorter alternative for most global singletons. Injectors are hierarchical, so a service provided in a component’s providers array gets a separate instance for that component and its children.

10. What are decorators in Angular?

Decorators are functions, written with @, that attach metadata to a class or member so Angular knows how to treat it. The common ones are @Component, @Directive, @Pipe and @Injectable. Older code also uses member decorators like @Input(), @Output() and @ViewChild(); modern code mostly uses the signal-based functions input(), output(), model() and viewChild() instead. (Early Angular 2 material sometimes called these “annotations”, a term from the AtScript era; today they are simply TypeScript decorators.)

11. What are lifecycle hooks?

Lifecycle hooks are methods Angular calls at specific moments in a component’s life:

  • ngOnChanges: an input value changed.
  • ngOnInit: runs once after the first inputs are set; a common place to start loading data.
  • ngDoCheck: runs on every change detection check (use rarely).
  • ngAfterContentInit / ngAfterContentChecked: projected content is ready or checked.
  • ngAfterViewInit / ngAfterViewChecked: the component’s own view is ready or checked.
  • ngOnDestroy: clean up subscriptions, timers and listeners.

Modern alternatives include DestroyRef (inject it and call onDestroy), takeUntilDestroyed() for RxJS, and afterNextRender / afterEveryRender for code that must touch the rendered DOM.

12. How do components communicate with each other?

  • Parent to child: inputs, with input() or @Input().
  • Child to parent: outputs, with output() or @Output(), which emit events the parent binds to.
  • Both ways: model() inputs for two-way binding.
  • Parent reading a child: viewChild() queries.
  • Unrelated components: a shared service that holds state in signals or observables.
  • Across pages: route parameters and query parameters.

13. How does routing work in Angular?

The Angular router maps URLs to components so a single-page app can show different views without full page reloads. You define routes and register them with provideRouter(routes), place <router-outlet /> where routed components should appear, and navigate with routerLink="/products" or router.navigate() in code. Routes can have parameters (products/:id), child routes, guards, resolvers, redirects and lazy-loaded components. With withComponentInputBinding(), route parameters arrive directly as component inputs.

14. What is the Angular CLI?

The Angular CLI is the official command-line tool for creating and maintaining Angular projects. Common commands are ng new (create a project), ng serve (run a development server), ng generate component (scaffold code), ng build (production build), ng test (unit tests) and ng update (upgrade Angular with automatic code migrations). Builds use the esbuild-based application builder with a Vite-powered dev server; the older webpack builders are deprecated as of Angular 22.

Angular Interview Questions for Experienced Developers

15. What are signals?

Signals are Angular’s reactive primitive: a wrapper around a value that tells Angular exactly who depends on it. When a signal changes, only the computations and templates that read it update. There are three core functions:

  • signal() creates writable state, changed with set() or update().
  • computed() derives a read-only value from other signals; it is lazy and memoized.
  • effect() runs side effects, such as logging or syncing to localStorage, when the signals it reads change.
const price = signal(100);
const qty = signal(2);
const total = computed(() => price() * qty());

effect(() => console.log('Total is', total()));

qty.set(3); // total() is now 300

You read a signal by calling it, total(), including in templates. linkedSignal() creates a writable signal that resets when a source changes, which is useful for things like a selected item that depends on a list.

Angular interview questions and answers: Angular Signals at a Glance
Angular Signals at a Glance (quick reference)

16. What is the difference between signals and RxJS observables?

A signal always has a current value that you can read synchronously, so it fits state: what the UI shows right now. An observable is a stream of values over time that you subscribe to, so it fits events and asynchronous work: HTTP calls, WebSocket messages, debounced search input or combining several streams with operators like switchMap. Most apps use both. The @angular/core/rxjs-interop package converts between them with toSignal() and toObservable().

17. How does change detection work in Angular?

Change detection is how Angular keeps the DOM in sync with component data. Traditionally, Angular used the Zone.js library, which patches browser APIs such as events, timers and promises, so Angular knew when something might have changed and then checked the component tree. Since Angular 21, new apps are zoneless by default: Zone.js is not included, and Angular schedules change detection only when it is notified, for example when a signal read in a template changes, a template event handler runs, the async pipe receives a value, or markForCheck() is called. Zoneless apps have smaller bundles, cleaner stack traces and fewer unnecessary checks. Existing apps can switch with provideZonelessChangeDetection().

18. What is the OnPush change detection strategy?

With ChangeDetectionStrategy.OnPush, Angular skips checking a component unless there is a reason to: an input receives a new reference, an event fires inside the component, an async pipe emits, a signal it reads changes, or markForCheck() is called. This can cut a lot of wasted work in large component trees, but it means you must treat data immutably: mutating an array in place will not refresh an OnPush child. Since Angular 22, OnPush is the default for new applications, and the old default strategy has been renamed Eager.

Angular interview questions and answers: Angular Change Detection Options
Angular Change Detection Options (quick reference)

19. What is the difference between AOT and JIT compilation?

Angular templates must be compiled into JavaScript instructions. Ahead-of-Time (AOT) compilation does this during the build, so the browser downloads already compiled code, the Angular compiler is not shipped to users, the app renders faster, and template errors are caught at build time. Just-in-Time (JIT) compilation does it in the browser at runtime. AOT has been the default for both development and production builds since Angular 9, when the Ivy compiler and runtime replaced the older View Engine.

20. How do you lazy load code in Angular?

Lazy loading splits the app into chunks that download only when needed. For routes, use loadComponent for a single component or loadChildren for a group of child routes:

{
  path: 'admin',
  loadComponent: () => import('./admin/admin').then(m => m.Admin)
}

For parts of a template, use deferrable views. Everything inside a @defer block, including its components, directives and pipes, is split into a separate chunk and loaded on a trigger such as on viewport, on idle, on interaction or on timer(2s):

@defer (on viewport) {
  <app-comments />
} @placeholder {
  <p>Comments load when you scroll here.</p>
} @loading (minimum 300ms) {
  <app-spinner />
}

21. What is the difference between template-driven forms, reactive forms and Signal Forms?

  • Template-driven forms (FormsModule, ngModel) define the form in the template. They are quick for simple forms but harder to test and to build dynamically.
  • Reactive forms (ReactiveFormsModule) define the form model in TypeScript with FormGroup, FormControl and validators. They are typed, explicit and easy to unit test, which made them the usual choice for complex forms.
  • Signal Forms build the form on top of a signal model, with typed fields, built-in and custom validators, and state such as validity and dirtiness exposed as signals. They became production-ready in Angular 22 and are the recommended direction for new forms.

22. How do HttpClient and interceptors work?

HttpClient is Angular’s service for HTTP requests. It returns observables, parses JSON automatically, and is enabled with provideHttpClient(). Interceptors sit between your code and the network, so you can add auth headers, log requests, retry failures or handle errors in one place. Modern interceptors are plain functions:

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = inject(AuthService).token();
  const authReq = token
    ? req.clone({ setHeaders: { Authorization: 'Bearer ' + token } })
    : req;
  return next(authReq);
};

// app.config.ts
providers: [provideHttpClient(withInterceptors([authInterceptor]))]

Requests are immutable, which is why the interceptor clones the request before changing it. For the HTTP concepts underneath, such as methods, status codes and CORS, see our HTTP interview questions.

23. What are route guards?

Guards decide whether navigation may happen. The main types are canActivate (enter a route), canActivateChild, canDeactivate (leave, for example with unsaved changes) and canMatch (whether a route definition should match at all, which also prevents its lazy code from loading). Modern guards are functions that can use inject():

export const authGuard: CanActivateFn = () => {
  const auth = inject(AuthService);
  const router = inject(Router);
  return auth.isLoggedIn() ? true : router.parseUrl('/login');
};

A guard returns true, false or a UrlTree to redirect. Guards improve the user experience but are not security: the server must still check every request.

24. What are resource and httpResource?

They bring asynchronous data into the signal world. resource() runs an async loader whenever the signals it depends on change, and exposes the result as signals: value(), isLoading(), error() and status(). httpResource() does the same for HTTP requests built on HttpClient:

userId = input.required<string>();
user = httpResource<User>(() => '/api/users/' + this.userId());

When userId changes, the request re-runs automatically and an older in-flight request is cancelled. Both APIs are production-ready as of Angular 22.

25. What is server-side rendering and hydration in Angular?

With server-side rendering (SSR), the server renders the HTML for a page, so users and search engines see content before the JavaScript loads. You add it with ng add @angular/ssr or choose it in ng new. Hydration then lets Angular reuse that server-rendered DOM in the browser instead of destroying and recreating it, which avoids flicker and improves Core Web Vitals. Incremental hydration goes further: parts of the page wrapped in @defer blocks stay as static HTML until a trigger such as hydrate on viewport fires. Event replay records clicks that happen before hydration finishes and replays them afterwards.

26. How do you test an Angular application?

Unit and component tests use TestBed to configure a testing module and create components with their dependencies, which you can replace with test doubles. Since Angular 21, new CLI projects use Vitest as the default test runner. Karma has been deprecated since 2023, though existing Jasmine and Karma setups are still supported. Angular CDK component harnesses let tests interact with components such as Material dialogs without depending on their internal DOM. For end-to-end tests, teams usually use Playwright or Cypress; the old Protractor tool has reached end of life.

27. How do you improve the performance of an Angular app?

  • Use signals and OnPush (the defaults in new apps) so only the affected parts of the view update.
  • Always give @for a stable track key, such as an ID, so the DOM is reused.
  • Lazy load routes and use @defer for heavy, below-the-fold content.
  • Move expensive calculations out of templates into computed() signals or pure pipes.
  • Use NgOptimizedImage (ngSrc) for images, which sets priorities, lazy loading and sizes.
  • Enable SSR with hydration for faster first paint on content-heavy pages.
  • Set bundle budgets in angular.json and inspect bundle size after each build.
  • Virtualize very long lists with the CDK virtual scroll viewport.

Rendering lots of data in charts is a common bottleneck; our guide to JavaScript graph libraries compares options that perform well with large datasets.

AngularJS Interview Questions

AngularJS reached end of support on December 31, 2021, but many companies still run AngularJS apps or are migrating them, so these AngularJS interview questions still come up for maintenance and migration roles.

28. What is $scope in AngularJS?

$scope is the object that connects a controller to its view. Properties and functions you put on $scope are available in the template, and changes on either side are kept in sync. Scopes form a hierarchy that mirrors the DOM: child scopes inherit prototypically from their parents, and $rootScope sits at the top. Scopes can also watch expressions ($watch) and send events up or down the tree ($emit and $broadcast).

29. What is the digest cycle in AngularJS?

The digest cycle is how AngularJS detects changes. Every binding and $watch registers a watcher. During a digest, AngularJS runs every watcher, compares the current value with the previous one, and runs listeners for those that changed. Because a listener can change other values, it repeats the loop until nothing changes, giving up with an “infdig” error after 10 iterations. Code that changes data outside AngularJS, such as a jQuery callback or a setTimeout, must call $scope.$apply() to start a digest.

$scope.$watch('qty', function (newVal, oldVal) {
  $scope.total = newVal * $scope.price;
});

Thousands of watchers make every digest slow, which is one of the main reasons Angular moved to a different change detection model.

30. What is the difference between a service, a factory and a provider in AngularJS?

All three create singletons that AngularJS can inject. A factory is a function whose return value becomes the service. A service is a constructor function that AngularJS calls with new. A provider is the most flexible: it exposes a $get function and can be configured in a config() block before the app runs. Factories and services are actually shortcuts built on providers.

app.factory('Api', function ($http) {
  return { getUsers: function () { return $http.get('/api/users'); } };
});

app.service('Logger', function () {
  this.log = function (msg) { console.log(msg); };
});

app.provider('Config', function () {
  var base = '/api';
  this.setBase = function (b) { base = b; };
  this.$get = function () { return { base: base }; };
});

31. What are filters in AngularJS?

Filters format values in templates and are applied with the pipe character: {{ amount | currency }}. Built-in filters are currency, date, filter, json, limitTo, lowercase, number, orderBy and uppercase, and you can create your own with app.filter(). In Angular, filters became pipes. Angular deliberately has no built-in filter or orderBy pipe, because running them on every check was a common source of slow AngularJS apps; sorting and filtering belong in the component.

32. What are directives in AngularJS, and how can they be used?

AngularJS directives are markers on DOM elements that attach behavior, such as the built-in ng-model, ng-repeat, ng-if, ng-show and ng-click. Custom directives are created with app.directive(), and the restrict option controls how they can be used: as an element (E), an attribute (A), a class (C) or a comment (M). The default is EA. AngularJS 1.5 added .component(), a simpler directive with a template and controller, which is the closest equivalent to an Angular component.

33. What is jqLite?

jqLite is a small subset of jQuery built into AngularJS. It covers the DOM operations AngularJS itself needs, such as adding classes, reading attributes and binding events, and you reach it through angular.element(). If the full jQuery library is loaded before AngularJS, angular.element uses jQuery instead. jqLite deliberately leaves out features like selectors by class name and animations.

34. How do you migrate from AngularJS to Angular?

Because AngularJS no longer receives security fixes from Google, migration is the long-term answer. The common approach is an incremental migration with ngUpgrade: you run AngularJS and Angular side by side in one hybrid app, then convert services and components one at a time, with upgraded or downgraded pieces bridging the two. Preparing the AngularJS code first helps a lot: move to TypeScript, use .component() instead of controllers, and follow a one-component-per-file structure. For small apps, a rewrite is often simpler. Companies that cannot migrate quickly sometimes buy commercial extended support for AngularJS in the meantime.

Conclusion

Most Angular interview questions come back to a few ideas: components and templates, how data flows through bindings and services, and how Angular decides what to re-render. If you can explain signals, zoneless change detection and OnPush clearly, and show how standalone components, the new control flow and @defer change the way apps are built, you will stand out from candidates who only know older Angular. If you were asked an Angular or AngularJS question recently that is not here, share it in the comments and we can work through it together.

Sources and further reading

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *