Examness

Web & Design

Angular Interview Questions

Modules, DI, RxJS, change detection and routing.

239 questions

  1. 1.

    What are the three phases of AOT?

    Beginner

    The AOT compiler works in three phases,

    1. Code Analysis In this phase, the TypeScript compiler and AOT collector create a representation of the source. 2. Code Generation It handles the interpretation as well as places restrictions on what it interprets. 3. Template Type Checking In this phase, the Angular template compiler uses the TypeScript compiler to validate the binding expressions in templates.

    ↥ back to top

  2. 2.

    What is Angular Universal?

    Beginner

    Angular Universal is a server-side rendering module for Angular applications in various scenarios. This is a community driven project and available under @angular/platform-server package. Recently Angular Universal is integrated with Angular CLI.

    ↥ back to top

  3. 3.

    What are the limitations with web workers?

    Beginner
    1. Some environments or platforms(like @angular/platform-server) used in Server-side Rendering, do not support Web Workers. In this case we need to provide a fallback mechanism to perform the computations to work in this environments.
    2. Running Angular in web worker using @angular/platform-webworker is not yet supported in Angular CLI.

    ↥ back to top

  4. 4.

    What is Ivy in Angular?

    Beginner

    Ivy is Angular\'s modern compilation and rendering engine, introduced as opt-in in Angular 8 and made the default engine in Angular 9.

    Key improvements over the previous View Engine:

    AreaView EngineIvy
    Bundle sizeLarger bundlesSmaller bundles via better tree-shaking
    Build speedSlower rebuildsFaster incremental compilation
    DebuggingLess informative stack tracesHuman-readable component debug info in DevTools
    Type checkingLimited template type-checkStrict template type checking
    Standalone componentsNot supportedFully supported (Angular 14+)

    Ivy powers modern Angular features:

    • Standalone components (Angular 14+) — Components without NgModule
    • Typed reactive forms (Angular 14+)
    • Required `@Input()` (Angular 16+)
    • Signals (Angular 17+)
    // Standalone component (Ivy-powered, no NgModule needed)
    @Component({
      selector: 'app-hello',
      standalone: true,
      imports: [CommonModule],
      template: `<p>Hello {{ name }}</p>`
    })
    export class HelloComponent {
      name = 'Angular';
    }

    ↥ back to top

  5. 5.

    What is TypeScript and why does Angular use it?

    Beginner

    TypeScript is a statically-typed superset of JavaScript developed by Microsoft. Angular uses TypeScript for the following benefits:

    1. Static typing — Catch type errors at compile time rather than runtime.

    // JavaScript — error only discovered at runtime
    function add(a, b) { return a + b; }
    add(1, '2'); // Returns '12' (string concatenation — silent bug)
    
    // TypeScript — error caught immediately by the compiler
    function addNumbers(a: number, b: number): number { return a + b; }
    // addNumbers(1, '2'); ERROR: Argument of type 'string' is not assignable to 'number'

    2. Interfaces & Types — Define contracts for data structures.

    interface User {
      id: number;
      name: string;
      email: string;
      role?: 'admin' | 'user'; // Optional union type
    }

    3. Decorators — Enable Angular\'s metadata system (@Component, @Injectable, @Input, etc.).

    4. Better IDE support — Rich autocompletion, inline documentation, and refactoring tools.

    5. Access modifierspublic, private, protected enforce encapsulation.

    6. Generics — Write reusable, type-safe code.

    getItems<T>(url: string): Observable<T[]> {
      return this.http.get<T[]>(url);
    }

    ↥ back to top

  6. 6.

    What is a custom pipe?

    Beginner

    A pipe is a class decorated with pipe metadata @Pipe() decorator, which you import from the core Angular library

    @Pipe({name: 'myCustomPipe'})

    The pipe class implements the PipeTransform() interface transform method that accepts an input value followed by optional parameters and returns the transformed value.

    interface PipeTransform {
      transform(value: any, ...args: any[]): any
    }

    The @Pipe() decorator allows to define the pipe name that you'll use within template expressions. It must be a valid JavaScript identifier.

    template: `{{someInputValue | myCustomPipe: someOtherValue}}`

    Example:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({name: 'customFileSizePipe'})
    export class FileSizePipe implements PipeTransform {
      transform(size: number, extension: string = 'MB'): string {
        return (size / (1024 * 1024)).toFixed(2) + extension;
      }
    }

    Now you can use the above pipe in template expression as below,

      template: `
        <h2>Find the size of a file</h2>
        <p>Size: {{288966 | customFileSizePipe: 'GB'}}</p>
      `

    ↥ back to top

  7. 7.

    What are Template-Driven Forms in Angular?

    Beginner

    Template-driven forms use ngModel and form directives in the template to implicitly build the form model. They are suitable for simple forms.

    Step 1: Import FormsModule

    @NgModule({ imports: [FormsModule] })
    export class AppModule {}

    Step 2: Create the form template

    <form #loginForm="ngForm" (ngSubmit)="onSubmit(loginForm)">
      <input
        type="email"
        name="email"
        [(ngModel)]="user.email"
        required
        email
        #emailField="ngModel">
      <div *ngIf="emailField.invalid && emailField.touched">
        <span *ngIf="emailField.errors?.['required']">Email is required</span>
        <span *ngIf="emailField.errors?.['email']">Invalid email format</span>
      </div>
      <input
        type="password"
        name="password"
        [(ngModel)]="user.password"
        required
        minlength="6">
      <button type="submit" [disabled]="loginForm.invalid">Login</button>
    </form>
    export class LoginComponent {
      user = { email: '', password: '' };
    
      onSubmit(form: NgForm) {
        if (form.valid) {
          console.log(form.value);
        }
      }
    }

    ↥ back to top

  8. 8.

    What are the types of cache in browsers?

    Beginner

    There are two types of cache in the browser: browser-managed cache and application-managed cache (service worker).

    • Browser-managed caches are a temporary storage location on computer for files downloaded by browser to display websites. Files that are cached locally include any documents that make up a website, such as HTML files, CSS style sheets, JavaScript scripts, as well as graphic images and other multimedia content. This cache is managed automatically by the browser and is not available offline.
    • Application-managed caches are created using the Cache API independent of the browser-managed caches. This API is available to applications (via window.caches) and the service worker. Application- managed caches hold the same kinds of assets as a browser cache but are accessible offline (e.g. by the service worker to enable offline support).This cache is managed by developers who implement scripts that use the Cache API to explicitly update items in named cache objects.

    ↥ back to top

  9. 9.

    How do you listen for events in a component?

    Beginner

    HostListener or via elementRef.nativeElement

    ↥ back to top

  10. 10.

    What is shadow DOM? How is it helping Angular to perform better?

    Beginner

    Shadow DOM basically allows group of DOM implementation to be hidden inside a single element and encapsulate styles to the element. Whenever we create a component, Angular puts its template into a shadowRoot, which is the Shadow DOM of that particular component.

    Example:

    @Component({
      templateUrl: 'card.html',
      styles: [`
        .card {
          height: 70px;
          width: 100px;
        }
      `],
      encapsulation: ViewEncapsulation.Native
      // encapsulation: ViewEncapsulation.None
      // encapsulation: ViewEncapsulation.Emulated is default 
    })
    • ViewEncapsulation.None: - No Shadow DOM at all. Therefore, also no style encapsulation.
    • ViewEncapsulation.Emulated: - No Shadow DOM but style encapsulation emulation.
    • ViewEncapsulation.Native: - Native Shadow DOM enabled.

    ↥ back to top

  11. 11.

    What are entryComponents?

    Beginner

    An entry component is any component that Angular loads imperatively. There are two main kinds of entry components:

    • The bootstrapped root component.
    • A component you specify in a route definition.
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpClientModule,
        AppRoutingModule
      ],
      providers: [],
      bootstrap: [AppComponent] // bootstrapped entry component
    })

    A bootstrapped component is an entry component that Angular loads into the DOM during the bootstrap process (application launch).

    ↥ back to top

  12. 12.

    What is Ng-Content/Content Projection?

    Beginner

    The tag as a placeholder for dynamic content, then when the template is parsed Angular will replace that placeholder tag with your content.

    They are used to create configurable components. This means the components can be configured depending on the needs of its user. This is well known as Content Projection. Components that are used in published libraries make use of to make themselves configurable.

    Example

    <!-- project-content.html -->
    <div class="heading">
      <h1>Welcome to Content Projection</h1>
    </div>
    <div class="body">
      <div>Some Content...</div>
    </div>
    <div class="footer">
      <ng-content></ng-content>
    </div>
    <project-content>
      <div>This is custom footer...</div>
    </project-content>

    ↥ back to top

  13. 13.

    What does lean component mean to you?

    Beginner

    A lean component is a component which solely purpose is to display data to user. This means such component delegates data fetching, bussiness logic, input validation etc. to other classes like models, services, redux effects/actions etc. Lean component follows single responsibility principle.

    ↥ back to top

  14. 14.

    What is hammerjs in angular?

    Beginner

    HammerJS gives us access to mobile gesture events that are not normally found in the browser, including tap, swipe, pan, pinch, press, and rotate.

    npm install --save hammerjs

    Add the import to main.ts to make the events globally available in your application.

    import 'hammerjs';
    
    if (environment.production) {
      enableProdMode();
    }
    
    platformBrowserDynamic().bootstrapModule(AppModule)
      .catch(err => console.log(err));

    Gesture Recognizers:

    • Pan: A Pan gesture is recognized when a pointer is down and moved within a set direction. The pan gesture is commonly used when scrolling through a set of items.
    • Pinch: A Pinch gesture is recognized when two or more pointers are moving toward or away from each other. The pinch gesture is commonly used for zooming in or out.
    • Press: A Press gesture is recognized when the pointer is being held down for a set amount of time. This is commonly used for long presses.
    • Rotate: A Rotate gesture is recognized when a set amount of pointers, minimum of 2, are moving in a circular motion. This is commonly used to rotate items.
    • Swipe: A Swipe gesture is recognized when a pointer is moving at a set speed for a set minimum amount of distance. This is commonly used to flip between items within a UI. Instead of scrolling, it is more useful to swap out items in a set direction.
    • Tap: A Tap gesture is recognized when a user taps the screen. This is commonly used for button presses.

    ↥ back to top

  15. 15.

    What is Interpolation?

    Beginner

    Interpolation is a special syntax that Angular converts into property binding. It is a convenient alternative to property binding. It is represented by double curly braces({{ }}). The text between the braces is often the name of a component property. Angular replaces that name with the string value of the corresponding component property.

    <h3>
      {{title}}
      <img src="{{url}}" style="height:30px">
    </h3>

    In the example above, Angular evaluates the title and url properties and fills in the blanks, first displaying a bold application title and then a URL.

    ↥ back to top

  16. 16.

    What is an observable?

    Beginner

    An Observable is a unique Object similar to a Promise that can help manage async code. Observables are not part of the JavaScript language so we need to rely on a popular Observable library called RxJS. The observables are created using new keyword.

    import { Observable } from 'rxjs';
    
    const observable = new Observable(observer => {
      setTimeout(() => {
        observer.next('Hello from a Observable!');
      }, 2000);
    });

    ↥ back to top

  17. 17.

    What are the utility functions provided by RxJS?

    Beginner

    The RxJS library also provides below utility functions for creating and working with observables.

    1. Converting existing code for async operations into observables
    2. Iterating through the values in a stream
    3. Mapping values to different types
    4. Filtering streams
    5. Composing multiple streams

    ↥ back to top

  18. 18.

    What is angular CLI?

    Beginner

    Angular CLI(Command Line Interface) is a command line interface to scaffold and build angular apps using nodejs style (commonJs) modules. You need to install using below npm command,

    npm install @angular/cli@latest

    Below are the list of few commands, which will come handy while creating angular projects

    1. Creating New Project ng new 2. Generating Components, Directives & Services ng generate/g

    The different types of commands would be,

    • ng generate class my-new-class: add a class to your application
    • ng generate component my-new-component: add a component to your application
    • ng generate directive my-new-directive: add a directive to your application
    • ng generate enum my-new-enum: add an enum to your application
    • ng generate module my-new-module: add a module to your application
    • ng generate pipe my-new-pipe: add a pipe to your application
    • ng generate service my-new-service: add a service to your application

    3. Running the Project ng serve

    ↥ back to top

  19. 19.

    What is Style function?

    Beginner

    The style function is used to define a set of styles to associate with a given state name. You need to use it along with state() function to set CSS style attributes. For example, in the close state, the button has a height of 100 pixels, an opacity of 0.8, and a background color of green.

    state('close', style({
      height: '100px',
      opacity: 0.8,
      backgroundColor: 'green'
    })),

    Note: The style attributes must be in camelCase

    ↥ back to top

  20. 20.

    What is an Angular Module?

    Beginner

    In Angular, a module is a mechanism to group components, directives, pipes and services that are related, in such a way that can be combined with other modules to create an application.

    import { NgModule }      from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppComponent }  from './app.component';
    
    @NgModule ({
        imports:      [ BrowserModule ],
        declarations: [ AppComponent ],
        bootstrap:    [ AppComponent ]
    })
    export class AppModule { }

    The NgModule decorator has three options

    • The imports option is used to import other dependent modules. The BrowserModule is required by default for any web based angular application
    • The declarations option is used to define components in the respective module
    • The bootstrap option tells Angular which Component to bootstrap in the application

    ↥ back to top