Skip to content

Angular Interview Questions

1. What is Angular?

Angular is a platform and framework for building single-page client applications using HTML and TypeScript. It is written in TypeScript and provides core functionality like dependency injection, routing, forms, and HTTP communication to build dynamic and scalable web apps.

2. What are Structural Directives? Can you give examples?

Structural directives are directives that change the DOM layout by adding and removing DOM elements. They are typically denoted by an asterisk (*) prefix.

Examples: * *ngIf: Conditionally includes a template based on the value of an expression. * *ngFor: Iterates over a list and renders a template for each item. * *ngSwitch: Switches among alternative views.

3. How does Angular bootstrap your application?
  1. The main.ts file is the entry point.
  2. It calls platformBrowserDynamic().bootstrapModule(AppModule).
  3. Angular loads the root module (AppModule).
  4. AppModule specifies the bootstrap component (usually AppComponent).
  5. Angular instantiates AppComponent and inserts it into the index.html file (usually inside <app-root>).
3. What is the Shadow DOM?

Shadow DOM is a web standard that offers component style and markup encapsulation. It allows a component to have its own isolated DOM tree that is separate from the main document DOM. * In Angular, ViewEncapsulation settings (Emulated, ShadowDom, None) control how styles are applied and if they bleed in/out.

4. What is an HTTP Interceptor? What are some keywords?

An HTTP Interceptor intercepts and handles an HttpRequest or HttpResponse. * Usage: Add auth tokens to headers, logging, error handling, caching. * Keywords: HttpInterceptor (interface), intercept() (method), next.handle(req) (to pass control).

5. What is the difference between Reactive and Template Driven Forms?
Feature Reactive Forms Template-Driven Forms
Approach Explicit, created in component class. Implicit, created by directives in template.
Data Model Structured and immutable. Unstructured and mutable.
Testing Easier (logic is in class). Harder (requires rendering).
Validation Defined in code (functions). Defined in template (attributes).
Scalability Better for complex forms. Better for simple forms.
6. How are Directives different from Components?
  • Component: A directive with a template. It controls a patch of screen. It is the fundamental building block.
  • Directive: Adds behavior to an existing element or changes the DOM structure. It doesn't necessarily have a view (template).
  • Note: All components are directives, but not all directives are components.
7. What makes up an Angular View?

An Angular View is composed of: 1. Template: HTML with Angular syntax. 2. Class (Component): TypeScript code handling logic and data. 3. Styles: CSS/SCSS for the view. 4. Metadata: Decorator (@Component) linking everything.

8. How can we handle routing in our Angular applications?

Using the Angular Router (@angular/router). 1. Define routes in app-routing.module.ts (path -> component mapping). 2. Use <router-outlet> in the template to display the routed component. 3. Use routerLink directive for navigation links.

9. What is FormBuilder?

FormBuilder is a service in Reactive Forms that provides syntactic sugar for creating instances of FormControl, FormGroup, and FormArray. It makes the code cleaner compared to new FormGroup(...).

10. Explain each keyword used in NgModule.
  • declarations: Components, Directives, and Pipes that belong to this module.
  • imports: Other modules whose exported classes are needed by component templates in this module.
  • exports: The subset of declarations that should be visible and usable in the templates of other modules.
  • providers: Services (creators) that this module contributes to the global collection of services.
  • bootstrap: The main application view, called the root component (only in the root module).
11. What is a Service and Dependency Injection?
  • Service: A class with a specific purpose (e.g., fetching data, logging) that can be shared across components.
  • Dependency Injection (DI): A coding pattern where a class asks for dependencies from external sources rather than creating them itself. Angular's DI framework provides declared dependencies (services) to components when they are instantiated.
12. How is an Observable different from a Promise?
Feature Observable (RxJS) Promise (Native JS)
Values Emits multiple values over time. Emits single value (resolve/reject).
Execution Lazy (doesn't start until subscribed). Eager (starts immediately on creation).
Cancellation Cancellable (unsubscribe). Not cancellable.
Operators Powerful operators (map, filter, retry). Limited methods (.then).
13. What is a Pipe?

A Pipe takes in data as input and transforms it to a desired output for display. * Examples: DatePipe (formats date), UpperCasePipe, CurrencyPipe. * Syntax: {{ value | pipeName }}.

14. How can we protect our routes when users are not logged in?

Using Route Guards (interfaces implementing CanActivate). * Logic inside canActivate() checks if user is authenticated. If yes, return true; else, redirect to login and return false.

15. What is a BehaviorSubject?

A BehaviorSubject is a type of Subject (Observable) that requires an initial value and always emits its current value to new subscribers immediately upon subscription.

16. How can we pass data between components?
  1. Parent to Child: @Input property.
  2. Child to Parent: @Output property with EventEmitter.
  3. Sibling/Unrelated: Shared Service (using Subject/BehaviorSubject) or State Management (NgRx).
  4. ViewChild/ContentChild: Access child component reference.
17. How do we catch errors in Observables?

Using the catchError operator in the pipe.

observable$.pipe(
  catchError(error => {
    // handle error
    return throwError(error);
  })
).subscribe(...)

18. What is the default testing library in Angular? The test runner?
  • Testing Library/Framework: Jasmine (for writing tests).
  • Test Runner: Karma (for running tests in the browser).
19. What is Property Binding?

A one-way data binding mechanism from Component to View (DOM property). * Syntax: [property]="expression" * Example: <img [src]="imageUrl">

20. How can we create custom Directives?
  1. Create a class with the @Directive decorator.
  2. Define a selector (e.g., [appHighlight]).
  3. Inject ElementRef to access the host DOM element.
  4. Implement logic (e.g., change background color on mouseover).
  5. Register in NgModule declarations.
21. What is the file compilation order when an Angular application starts?
  1. angular.json (Configuration)
  2. main.ts (Entry point)
  3. app.module.ts (Root Module)
  4. app.component.ts (Bootstrap Component)
22. What is the purpose of the polyfills.ts file?

It imports scripts required to run an Angular application in browsers that lack native support for certain modern web standards (e.g., older IE versions). It ensures cross-browser compatibility.

23. What is a Subject?

A Subject is a special type of Observable that is also an Observer. * It is multicast: It allows values to be multicasted to many Observers (subscribers share the same execution). * You can manually call next(), error(), and complete() on it.

24. How can we emit values through Observables?
  • Standard Observables typically emit values via the callback passed to the constructor.
  • Subjects (Subject, BehaviorSubject) allow imperative emission using the .next(value) method.
25. What is ngModel?

ngModel is a directive used for Two-Way Data Binding. It binds an input, select, or textarea element to a property on the scope. It requires FormsModule. * Syntax: [(ngModel)]="property" (Banana-in-a-box).

26. How can we make HTTP requests?

Using HttpClient (from HttpClientModule). * Inject HttpClient into a service. * Use methods like this.http.get(url), this.http.post(url, body). * These methods return Observables.

27. How can we conditionally render an element?

Using the *ngIf structural directive. * <div *ngIf="isLoggedIn">Welcome</div>

28. What is NgRx?

NgRx is a state management library for Angular applications, inspired by Redux. It uses RxJS Observables. * Core concepts: Store, Actions, Reducers, Selectors, Effects. * It provides a single source of truth for application state.

29. How is a Subject different from an Observable?
  • Observable: Unicast (each subscriber gets independent execution), Passive (data source pushes).
  • Subject: Multicast (subscribers share execution), Active (can manually trigger next()).
30. When does ngOnChanges run?

It runs when Angular sets or resets data-bound input properties (properties decorated with @Input). * It runs before ngOnInit. * It runs every time the input value changes (by reference).

31. What is ChangeDetection? What are the different strategies?

Change Detection is the mechanism Angular uses to synchronize the application state with the UI.

Strategies: 1. Default: Checks every component in the tree whenever any event occurs (click, timer, HTTP). 2. OnPush: Only checks the component if: * The @Input reference changes. * An event originated from the component or its children. * An Observable using async pipe emits. * Manually triggered via ChangeDetectorRef.

32. What are some benefits of Typescript?
  1. Static Typing: Catches errors at compile-time.
  2. IntelliSense: Better code completion and tooling support.
  3. OOP features: Interfaces, Classes, Generics, Access Modifiers.
  4. Readability: Code is easier to understand and maintain.
33. What is the difference between ng-template, ng-container, and ng-content?
  • <ng-template>: Defines a template that is not rendered by default. It is used with structural directives (like *ngIf, *ngFor).
  • <ng-container>: A logical container that allows grouping elements but does not get rendered in the DOM. Good for applying structural directives without adding extra divs.
  • <ng-content>: Used for Content Projection (slot). It acts as a placeholder where content from the parent component is inserted.
34. What is the difference between RxJS “of” and “from”?
  • of(a, b, c): Emits the arguments as values in sequence. of([1, 2]) emits the array as a single value.
  • from([1, 2]): Converts an Observable-like object (Array, Promise, Iterator) into an Observable. from([1, 2]) emits each item in the array individually (1, then 2).
35. What does the async pipe do?

The async pipe (| async) subscribes to an Observable (or Promise) directly in the template and returns the latest emitted value. * It automatically unsubscribes when the component is destroyed (preventing memory leaks). * It triggers change detection.

36. What is a ReplaySubject?

A ReplaySubject is a Subject that records multiple values from the Observable execution and replays them to new subscribers. You can specify the buffer size (how many previous values to replay).

37. What are some RxJS Operators?
  • Creation: of, from, interval.
  • Transformation: map, flatMap, switchMap, concatMap.
  • Filtering: filter, take, debounceTime, distinctUntilChanged.
  • Combination: combineLatest, merge, concat, forkJoin.
  • Error Handling: catchError, retry.