Wednesday, April 30, 2025

Angular

 Here's a comprehensive table of new features from Angular 6 to Angular 16, showing version-wise enhancements. After the table, you'll find detailed explanations of the most impactful features per version.


πŸ”’ Angular 6 to Angular 16: Feature Summary Table

Angular VersionRelease DateMajor Features
Angular 6May 2018Angular Elements, ng update, ng add, CLI workspaces
Angular 7Oct 2018Virtual scrolling, Drag & Drop, CLI prompts, Angular Material updates
Angular 8May 2019Differential loading, Web Workers, Dynamic imports, Ivy preview
Angular 9Feb 2020Ivy renderer by default, smaller bundles, improved testing
Angular 10Jun 2020New date range picker, stricter types, updated browser support
Angular 11Nov 2020Hot Module Replacement (HMR), faster builds, ESLint support
Angular 12May 2021Ivy everywhere, Webpack 5, Nullish Coalescing (??) support
Angular 13Nov 2021No View Engine, ESBuild, TypeScript 4.4, RxJS 7
Angular 14Jun 2022Standalone components, typed forms, improved CLI auto-imports
Angular 15Nov 2022Stable standalone APIs, directive composition API, better SSR
Angular 16May 2023Signals (reactivity model), SSR improvements, hydration, standalone stable

πŸ“˜ Detailed Features by Angular Version

πŸ”Ή Angular 6

  • Angular Elements: Embed Angular components as custom elements.

  • ng update and ng add: Simplify package updates and installing dependencies.

  • CLI Workspaces: Support for multiple projects in one workspace.

πŸ”Ή Angular 7

  • Virtual Scrolling: Load only visible items in long lists.

  • Drag & Drop: Integrated with Angular CDK.

  • CLI Prompts: Better CLI interactivity.

  • Better accessibility & Material updates.

πŸ”Ή Angular 8

  • Differential Loading: Separate bundles for modern and legacy browsers.

  • Dynamic Imports: For lazy loading using import().

  • Web Workers Support.

  • Ivy opt-in preview.

πŸ”Ή Angular 9

  • Ivy enabled by default: Improved compilation, tree-shaking, and debugging.

  • Smaller bundle size.

  • Improved Testing & build errors.

πŸ”Ή Angular 10

  • Date Range Picker in Angular Material.

  • Stricter project setup via ng new.

  • Updated dependencies like TS 3.9, TSLint, etc.

πŸ”Ή Angular 11

  • Hot Module Replacement (HMR) built-in for dev.

  • Faster Builds using updated build system.

  • ESLint Migration support.

  • Improved logging & analytics.

πŸ”Ή Angular 12

  • View Engine removed: Only Ivy supported.

  • Nullish Coalescing (??) Support.

  • Webpack 5 support, TS 4.2 support.

  • Deprecation of IE11.

πŸ”Ή Angular 13

  • Removed View Engine support.

  • ESBuild for faster builds.

  • TypeScript 4.4 and RxJS 7.

  • Dynamic component creation simplified.

πŸ”Ή Angular 14

  • Standalone Components (Preview): Component-based apps without NgModules.

  • Typed Reactive Forms: Full type safety for form controls.

  • Auto-imports in CLI and improved diagnostics.

πŸ”Ή Angular 15

  • Standalone APIs stable: Components, directives, pipes without NgModule.

  • Directive Composition API: Combine logic from multiple directives.

  • Improved SSR support and hydration prep.

πŸ”Ή Angular 16

  • Signals: Fine-grained reactivity system (similar to SolidJS).

  • Full Hydration: For server-side rendering.

  • Improved Inputs: @Input() with default values and required checks.

  • Zoneless Change Detection (experimental).

  • Developer Preview of DestroyRef, Enhanced lifecycle control.


Would you like a downloadable PDF or visual chart for this feature list?

1/2
You said:
ALL Interview question 100 questions and awser in deatil
ChatGPT said:

Certainly! Here's a curated list of 100 Angular interview questions and answers, categorized by experience level to help you prepare effectively:


πŸ”° Beginner-Level Angular Interview Questions (1–2 Years Experience)

  1. What is Angular?
    Angular is a TypeScript-based open-source web application framework developed by Google. It facilitates building dynamic single-page applications (SPAs) with features like two-way data binding, dependency injection, and modular architecture.

  2. What are the key features of Angular?
    Angular offers a component-based architecture, TypeScript support, two-way data binding, dependency injection, directives, pipes, and a powerful CLI for scaffolding and managing applications.

  3. Explain the difference between Angular and AngularJS.
    Angular (versions 2 and above) is a complete rewrite of AngularJS (version 1.x). Angular uses TypeScript, has a component-based architecture, and offers improved performance with Ahead-of-Time (AOT) compilation, whereas AngularJS is based on JavaScript and follows an MVC architecture.

  4. What is a component in Angular?
    A component is the fundamental building block of Angular applications. It controls a portion of the UI and consists of a TypeScript class, an HTML template, and optional CSS styles.

  5. How does data binding work in Angular?
    Angular supports one-way and two-way data binding. One-way binding updates the view from the model, while two-way binding synchronizes data between the model and the view using the [(ngModel)] syntax.

  6. What are directives in Angular?
    Directives are classes that add behavior to elements in Angular applications. There are three types: components (which are directives with templates), structural directives (e.g., *ngIf, *ngFor), and attribute directives (e.g., ngClass, ngStyle).

  7. What is Angular CLI and its benefits?
    Angular CLI is a command-line interface tool that automates project creation, configuration, development, and maintenance tasks. It streamlines processes like scaffolding components, services, and modules, running tests, and building applications.

  8. Explain the concept of modules in Angular.
    Modules in Angular, defined using the @NgModule decorator, help organize an application into cohesive blocks of functionality. They group related components, directives, pipes, and services, facilitating code reusability and maintainability.

  9. What is a service in Angular?
    A service is a class that encapsulates business logic, data retrieval, or other functionalities that can be shared across components. Services are typically injected into components using Angular's dependency injection system.

  10. How does routing work in Angular?
    Angular's Router module enables navigation between different views or components. Routes are defined in a configuration array, mapping paths to components, and navigation is handled using directives like routerLink or programmatically via the Router service.


⚙️ Intermediate-Level Angular Interview Questions (2–4 Years Experience)

  1. What is dependency injection in Angular?
    Dependency injection is a design pattern where a class receives its dependencies from external sources rather than creating them internally. Angular's DI system provides dependencies to components and services, promoting modularity and testability.

  2. Explain the lifecycle hooks of an Angular component.
    Angular components have lifecycle hooks like ngOnInit, ngOnChanges, ngDoCheck, ngAfterViewInit, and ngOnDestroy, which allow developers to tap into key moments of a component's lifecycle for initialization, change detection, and cleanup.

  3. What is Ahead-of-Time (AOT) compilation?
    AOT compilation converts Angular HTML and TypeScript code into efficient JavaScript code during the build phase, before the browser downloads and runs the code. This leads to faster rendering and improved performance.

  4. How does Angular handle forms?
    Angular provides two approaches for handling forms: Template-driven forms, which rely on directives in the template, and Reactive forms, which are model-driven and offer more control and scalability.

  5. What are pipes in Angular?
    Pipes are functions that transform data in templates. Angular includes built-in pipes like DatePipe, UpperCasePipe, and CurrencyPipe, and developers can create custom pipes for specific transformations.

  6. Explain the concept of observables in Angular.
    Observables, provided by RxJS, are used in Angular for handling asynchronous data streams, such as HTTP requests or user input events. They allow for powerful operations like mapping, filtering, and combining streams.

  7. What is change detection in Angular?
    Change detection is the mechanism by which Angular determines when to update the view in response to changes in the application's state. Angular uses zones to detect changes and update the DOM accordingly.

  8. How do you implement lazy loading in Angular?
    Lazy loading involves loading feature modules only when they're needed, reducing the initial load time. This is achieved by configuring routes with the loadChildren property and using dynamic imports.

  9. What are guards in Angular routing?
    Guards are interfaces that determine whether navigation to a route should be allowed. Types include CanActivate, CanDeactivate, Resolve, and CanLoad, each serving different purposes in route protection and data retrieval.

  10. How do you handle HTTP requests in Angular?
    Angular's HttpClient service is used to make HTTP requests. It returns observables, allowing for asynchronous operations and easy integration with RxJS operators for handling responses and errors.


πŸš€ Advanced-Level Angular Interview Questions (5+ Years Experience)

  1. What is the difference between ViewEncapsulation types in Angular?
    Angular offers three encapsulation modes: Emulated (default, emulates Shadow DOM), None (no encapsulation), and ShadowDom (uses native Shadow DOM). These modes determine how styles are scoped to components.

  2. Explain the role of NgZone in Angular.
    NgZone is a service that helps Angular detect and respond to asynchronous operations by triggering change detection. It ensures that the view reflects the latest state after events like setTimeout or HTTP responses.

  3. How does Angular's Ivy renderer improve performance?
    Ivy is Angular's next-generation rendering engine that offers faster compilation, smaller bundle sizes, improved debugging, and better type checking, enhancing overall application performance.

  4. What are Angular elements?
    Angular elements allow developers to create custom elements (web components) from Angular components, enabling integration with non-Angular applications and promoting reusability.

  5. How do you implement server-side rendering (SSR) in Angular?
    SSR in Angular is achieved using Angular Universal, which renders the application on the server, improving performance and SEO. It involves setting up a server-side app module and configuring a Node.js server.

  6. What is the purpose of the Renderer2 service in Angular?
    Renderer2 is an abstraction that allows for DOM manipulation in a way that maintains compatibility across different platforms, such as web browsers and servers. It provides methods for creating and modifying elements.

  7. Explain the concept of change detection strategies in Angular.
    Angular provides two change detection strategies: Default, which checks all components, and OnPush, which checks only when inputs change or events occur, leading to performance optimizations.

  8. How do you create a custom structural directive in Angular?
    A custom structural directive is created by implementing the Directive decorator and manipulating the DOM using TemplateRef and ViewContainerRef to add or remove elements based on conditions.

  9. What is the difference between ngOnInit and constructor in Angular?
    The constructor is used for dependency injection and initializing class members, while ngOnInit is a lifecycle hook called after the component's view has been initialized, suitable for fetching data and other setup tasks.

  10. How do you handle state management in Angular applications?
    State management can be handled using services with RxJS for simple cases or libraries like NgRx or Akita for more complex applications, providing a unidirectional data flow and centralized state management.


For a comprehensive list of 100 Angular interview questions and answers, including scenario-based and multiple-choice questions, you can refer to the following resources:

These resources provide detailed explanations and are updated regularly to reflect the latest Angular features and best practices.

If you need a downloadable PDF or a categorized list tailored to your experience level, feel free to ask!




OR 


Angular Version Features (6 to 16)

VersionRelease YearKey Features
Angular 62018- Angular CLI Workspaces
- Ivy Renderer (experimental)
- RxJS 6 support
- Tree-shakable providers
Angular 72018- CLI Prompts
- Virtual Scrolling (CDK)
- Drag & Drop (CDK)
- Angular Elements updates
Angular 82019- Differential Loading
- Ivy Opt-in
- Dynamic Imports for Lazy Loading
- Web Worker Support
Angular 92020- Ivy Renderer (stable)
- Smaller Bundle Sizes
- Improved AOT Compilation
- TypeScript 3.7 Support
Angular 102020- CommonJS Import Warnings
- New Date Range Picker (Material)
- Strict Mode Enhancements
Angular 112020- Automatic Font Inlining
- Hot Module Replacement (HMR)
- Experimental Webpack 5 Support
Angular 122021- Nullish Coalescing Support
- Stricter Types for Forms
- Ivy-Based Language Service
Angular 132021- Removal of View Engine
- IE11 Support Dropped
- Stable APF (Angular Package Format)
Angular 142022- Standalone Components (developer preview)
- Typed Reactive Forms
- Streamlined Page Title API
Angular 152022- Stable Standalone APIs
- Directive Composition API
- Improved Stack Traces
Angular 162023- Signals (reactive primitives)
- Non-destructive Hydration (SSR)
- Required Inputs
- Jest Testing Support

Detailed Features of Angular 16 124

1. Angular Signals

  • What: A new reactivity model inspired by Solid.js, enabling fine-grained change detection without Zone.js. Signals allow synchronous value access and dependency tracking.

  • Example:

    typescript
    Copy
    Download
    count = signal(0);  
    double = computed(() => this.count() * 2);  
    effect(() => console.log(this.double()));  
  • Impact: Improves runtime performance and simplifies state management. Zone.js becomes optional in future versions 410.

2. Non-Destructive Hydration (SSR)

  • What: Preserves server-rendered DOM during client-side hydration, eliminating flickering and improving Core Web Vitals (e.g., LCP).

  • Setup:

    typescript
    Copy
    Download
    bootstrapApplication(App, { providers: [provideClientHydration()] });  
  • Benefit: Up to 45% faster LCP in some applications 107.

3. Required Inputs

  • What: Enforces mandatory component inputs at compile time.

  • Syntax:

    typescript
    Copy
    Download
    @Input({ required: true }) title!: string;  
  • Use Case: Eliminates runtime checks for missing inputs 26.

4. Jest Testing Support

  • What: Experimental integration with Jest for unit testing, replacing Karma in future versions.

  • Setup:

    json
    Copy
    Download
    "test": { "builder": "@angular-devkit/build-angular:jest" }  

    610.

5. Router Input Binding

  • What: Binds route parameters (path/query/data) directly to component inputs without ActivatedRoute.

  • Example:

    typescript
    Copy
    Download
    @Input() userId!: string; // Maps to `/users?userId=123`  

    27.

6. esbuild + Vite Build System

  • What: Faster builds (72% improvement in cold production builds) using esbuild and Vite for development.

  • Enable: Update angular.json:

    json
    Copy
    Download
    "builder": "@angular-devkit/build-angular:browser-esbuild"  

    107.

7. Standalone Project Creation

  • What: Generate projects without NgModules using:

    bash
    Copy
    Download
    ng new --standalone  

    610.

8. RxJS Interop

  • What: Convert signals to observables and vice versa:

    typescript
    Copy
    Download
    count$ = toObservable(this.count);  
    data = toSignal(this.http.get('...'));  

    104.

9. DestroyRef & takeUntilDestroyed

  • What: Simplifies cleanup logic:

    typescript
    Copy
    Download
    destroyRef.onDestroy(() => /* cleanup */);  
    data$ = http.get('...').pipe(takeUntilDestroyed());  

    47.

10. CSP Support for Inline Styles

  • What: Adds ngCspNonce attribute or CSP_NONCE token for security compliance 210.


Summary

Angular 16 focuses on reactivity (Signals)SSR performance, and developer experience (standalone APIs, tooling). For a full migration guide, refer to the official Angular blog 10. Let me know if you'd like deeper dives into specific versions!



ORRRRRRRRRRRRRRRRR




100 Angular Interview Questions and Answers with Implementations

Angular Fundamentals

1. What is Angular and how does it differ from AngularJS?

Answer:
Angular is a TypeScript-based open-source web application framework led by Google. It's a complete rewrite of AngularJS with key differences:

  • Architecture: Angular uses component-based architecture while AngularJS uses MVC

  • Language: Angular uses TypeScript (superset of ES6) while AngularJS uses JavaScript

  • Mobile Support: Angular has built-in mobile support

  • Performance: Angular is faster due to better change detection and ahead-of-time (AOT) compilation

  • CLI: Angular has Angular CLI for project scaffolding

Implementation:

typescript
Copy
Download
// Angular component example
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<h1>Welcome to {{title}}!</h1>`,
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Angular App';
}

2. Explain Angular modules (NgModule)

Answer:
NgModule is a decorator that declares a compilation context for components. It:

  • Declares components, directives, pipes that belong to it

  • Makes some of them public (via exports) for other modules

  • Can import functionality from other modules

  • Can specify services providers available to its components

Implementation:

typescript
Copy
Download
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

3. What are Angular components?

Answer:
Components are the basic building blocks of Angular applications:

  • Control a portion of the UI (view)

  • Consist of a class (behavior) and template (view)

  • Can receive input and emit output

  • Have lifecycle hooks for different stages

Implementation:

typescript
Copy
Download
import { Component, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-greeting',
  template: `
    <h2>Hello {{name}}!</h2>
    <button (click)="sayHello()">Say Hello</button>
  `
})
export class GreetingComponent {
  @Input() name: string;
  @Output() hello = new EventEmitter<string>();

  sayHello() {
    this.hello.emit(`Hello from ${this.name}`);
  }
}

4. Explain data binding in Angular

Answer:
Data binding is synchronization between model and view:

  1. Interpolation{{value}} - Displays component value in template

  2. Property binding[property]="value" - Sets element property

  3. Event binding(event)="handler()" - Listens for events

  4. Two-way binding[(ngModel)]="property" - Combination of property and event binding

Implementation:

typescript
Copy
Download
@Component({
  selector: 'app-databinding',
  template: `
    <!-- Interpolation -->
    <p>{{title}}</p>
    
    <!-- Property binding -->
    <img [src]="imageUrl">
    
    <!-- Event binding -->
    <button (click)="onClick()">Click</button>
    
    <!-- Two-way binding -->
    <input [(ngModel)]="name">
    <p>Hello {{name}}!</p>
  `
})
export class DataBindingComponent {
  title = 'Data Binding';
  imageUrl = 'path/to/image.jpg';
  name = '';
  
  onClick() {
    console.log('Button clicked');
  }
}

5. What are Angular directives?

Answer:
Directives are classes that add behavior to elements:

  1. Component Directives: Components with templates

  2. Structural Directives: Change DOM layout (ngIf, ngFor, ngSwitch)

  3. Attribute Directives: Change appearance/behavior (ngStyle, ngClass)

Implementation:

typescript
Copy
Download
@Component({
  selector: 'app-directives',
  template: `
    <!-- Structural directive -->
    <div *ngIf="showContent">Visible content</div>
    <ul>
      <li *ngFor="let item of items">{{item}}</li>
    </ul>
    
    <!-- Attribute directive -->
    <p [ngClass]="{active: isActive}">Class binding</p>
    <p [ngStyle]="{color: textColor}">Style binding</p>
  `
})
export class DirectivesComponent {
  showContent = true;
  items = ['Item 1', 'Item 2', 'Item 3'];
  isActive = true;
  textColor = 'blue';
}

Components and Templates

6. Explain component lifecycle hooks

Answer:
Angular components have lifecycle hooks:

  1. ngOnChanges: When input properties change

  2. ngOnInit: After first ngOnChanges

  3. ngDoCheck: During every change detection run

  4. ngAfterContentInit: After content projected

  5. ngAfterContentChecked: After projected content checked

  6. ngAfterViewInit: After component's view initialized

  7. ngAfterViewChecked: After component's view checked

  8. ngOnDestroy: Before component is destroyed

Implementation:

typescript
Copy
Download
import { Component, Input, OnChanges, OnInit, DoCheck, 
         AfterContentInit, AfterContentChecked, 
         AfterViewInit, AfterViewChecked, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-lifecycle',
  template: `<p>Lifecycle Demo: {{name}}</p>`
})
export class LifecycleComponent implements OnChanges, OnInit, DoCheck,
  AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {
  
  @Input() name: string;

  ngOnChanges() {
    console.log('ngOnChanges');
  }
  
  ngOnInit() {
    console.log('ngOnInit');
  }
  
  ngDoCheck() {
    console.log('ngDoCheck');
  }
  
  ngAfterContentInit() {
    console.log('ngAfterContentInit');
  }
  
  ngAfterContentChecked() {
    console.log('ngAfterContentChecked');
  }
  
  ngAfterViewInit() {
    console.log('ngAfterViewInit');
  }
  
  ngAfterViewChecked() {
    console.log('ngAfterViewChecked');
  }
  
  ngOnDestroy() {
    console.log('ngOnDestroy');
  }
}

7. What is ViewEncapsulation in Angular?

Answer:
ViewEncapsulation determines how styles are applied:

  1. Emulated (default): Styles are scoped to component

  2. None: Styles are global

  3. ShadowDom: Uses browser's shadow DOM

Implementation:

typescript
Copy
Download
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-encapsulation',
  template: `<p class="demo">View Encapsulation Demo</p>`,
  styles: [`.demo { color: red; }`],
  encapsulation: ViewEncapsulation.Emulated // Can be None or ShadowDom
})
export class EncapsulationComponent {}

8. How to pass data between components?

Answer:

  1. Parent to Child: Using @Input()

  2. Child to Parent: Using @Output() and EventEmitter

  3. Sibling Components: Via parent or using a service

  4. Unrelated Components: Using services or state management

Implementation:

typescript
Copy
Download
// Parent to Child
@Component({
  selector: 'app-parent',
  template: `<app-child [message]="parentMessage"></app-child>`
})
export class ParentComponent {
  parentMessage = 'Hello from parent';
}

@Component({
  selector: 'app-child',
  template: `<p>{{message}}</p>`
})
export class ChildComponent {
  @Input() message: string;
}

// Child to Parent
@Component({
  selector: 'app-child',
  template: `<button (click)="sendMessage()">Send</button>`
})
export class ChildComponent {
  @Output() messageEvent = new EventEmitter<string>();
  
  sendMessage() {
    this.messageEvent.emit('Hello from child');
  }
}

@Component({
  selector: 'app-parent',
  template: `
    <app-child (messageEvent)="receiveMessage($event)"></app-child>
    <p>{{message}}</p>
  `
})
export class ParentComponent {
  message = '';
  
  receiveMessage($event) {
    this.message = $event;
  }
}

9. What are template reference variables?

Answer:
Template reference variables (#var) are references to DOM elements or directives:

  • Can be used in template to access element properties

  • Can be passed to methods

  • Can refer to Angular components/directives

Implementation:

typescript
Copy
Download
@Component({
  selector: 'app-template-ref',
  template: `
    <input #inputRef type="text">
    <button (click)="logValue(inputRef.value)">Log Value</button>
    
    <app-child #childRef></app-child>
    <button (click)="callChildMethod(childRef)">Call Child</button>
  `
})
export class TemplateRefComponent {
  logValue(value: string) {
    console.log(value);
  }
  
  callChildMethod(child: any) {
    child.childMethod();
  }
}

10. Explain content projection with ng-content

Answer:
Content projection (transclusion) allows inserting external content into a component:

  • Single slot: <ng-content></ng-content>

  • Multi-slot: <ng-content select="[selector]"></ng-content>

Implementation:

typescript
Copy
Download
// Projection component
@Component({
  selector: 'app-card',
  template: `
    <div class="card">
      <div class="header">
        <ng-content select="[card-header]"></ng-content>
      </div>
      <div class="content">
        <ng-content></ng-content>
      </div>
    </div>
  `
})
export class CardComponent {}

// Usage
@Component({
  selector: 'app-root',
  template: `
    <app-card>
      <div card-header>Custom Header</div>
      <p>This is the projected content</p>
    </app-card>
  `
})
export class AppComponent {}

Directives and Pipes

11. How to create a custom directive?

Answer:
Custom directives are created using @Directive decorator:

  1. Create a class with directive logic

  2. Decorate with @Directive

  3. Define selector (CSS selector)

  4. Optionally inject ElementRef to access host element

Implementation:

typescript
Copy
Download
import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  @Input() appHighlight = '';
  @Input() defaultColor = '';

  constructor(private el: ElementRef) {}

  @HostListener('mouseenter') onMouseEnter() {
    this.highlight(this.appHighlight || this.defaultColor || 'yellow');
  }

  @HostListener('mouseleave') onMouseLeave() {
    this.highlight('');
  }

  private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
  }
}

// Usage: <p [appHighlight]="'red'" [defaultColor]="'cyan'">Hover me!</p>

12. What are pure and impure pipes?

Answer:

  • Pure pipes: Only execute when input changes (default). Should be pure functions.

  • Impure pipes: Execute on every change detection cycle (can be expensive)

Implementation:

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

@Pipe({
  name: 'filter',
  pure: false // Makes it impure
})
export class FilterPipe implements PipeTransform {
  transform(items: any[], filterText: string): any {
    if (!items || !filterText) return items;
    return items.filter(item => 
      item.toLowerCase().includes(filterText.toLowerCase())
    );
  }
}

// Pure pipe example
@Pipe({ name: 'square' })
export class SquarePipe implements PipeTransform {
  transform(value: number): number {
    return value * value;
  }
}

13. How to create a custom pipe?

Answer:

  1. Create a class implementing PipeTransform

  2. Decorate with @Pipe

  3. Implement transform method

Implementation:

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

@Pipe({ name: 'initials' })
export class InitialsPipe implements PipeTransform {
  transform(name: string, length: number = 2): string {
    if (!name) return '';
    return name.split(' ')
      .map(part => part.charAt(0).toUpperCase())
      .join('')
      .substring(0, length);
  }
}

// Usage: {{ 'John Doe' | initials }} outputs "JD"

14. Explain ngFor trackBy

Answer:
trackBy improves performance by tracking items by unique identifier instead of object identity:

  • Reduces DOM manipulations

  • Helps Angular identify which items have changed

Implementation:

typescript
Copy
Download
@Component({
  selector: 'app-trackby',
  template: `
    <ul>
      <li *ngFor="let item of items; trackBy: trackById">
        {{item.name}}
      </li>
    </ul>
    <button (click)="refresh()">Refresh</button>
  `
})
export class TrackByComponent {
  items = [
    { id: 1, name: 'Item 1' },
    { id: 2, name: 'Item 2' }
  ];

  trackById(index: number, item: any): number {
    return item.id;
  }

  refresh() {
    this.items = [
      { id: 1, name: 'Updated Item 1' },
      { id: 2, name: 'Updated Item 2' },
      { id: 3, name: 'New Item 3' }
    ];
  }
}

15. What is ng-container and when to use it?

Answer:
<ng-container> is a logical container that doesn't render in DOM:

  • Groups elements without adding extra nodes

  • Useful with structural directives when you can't add wrapper elements

  • Can't have styles or event listeners

Implementation:

typescript
Copy
Download
@Component({
  selector: 'app-ngcontainer',
  template: `
    <div *ngIf="show">
      <ng-container *ngIf="condition; else elseTemplate">
        <p>Content 1</p>
        <p>Content 2</p>
      </ng-container>
      <ng-template #elseTemplate>
        <p>Else content</p>
      </ng-template>
    </div>
  `
})
export class NgContainerComponent {
  show = true;
  condition = true;
}

Services and Dependency Injection

16. What are Angular services?

Answer:
Services are singleton classes that:

  • Provide reusable business logic

  • Share data between components

  • Handle API communication

  • Are injectable via dependency injection

Implementation:

typescript
Copy
Download
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root' // Makes it a singleton
})
export class DataService {
  private data: string[] = [];

  addData(item: string) {
    this.data.push(item);
  }

  getData() {
    return this.data;
  }

  clearData() {
    this.data = [];
  }
}

// Usage in component
@Component({
  selector: 'app-service-demo',
  template: `...`
})
export class ServiceDemoComponent {
  constructor(private dataService: DataService) {}
  
  addItem(item: string) {
    this.dataService.addData(item);
  }
}

17. Explain dependency injection in Angular

Answer:
Dependency Injection (DI) is a design pattern where:

  • Dependencies are provided to classes rather than created internally

  • Angular's DI system creates and manages instances

  • Components declare dependencies in constructor

  • Providers determine how dependencies are created

Implementation:

typescript
Copy
Download
// Service
@Injectable({
  providedIn: 'root'
})
export class LoggerService {
  log(message: string) {
    console.log(message);
  }
}

// Component using DI
@Component({
  selector: 'app-di-demo',
  template: `...`
})
export class DiDemoComponent {
  constructor(private logger: LoggerService) {
    this.logger.log('Component created');
  }
}

// Module-level provider (alternative to providedIn)
@NgModule({
  providers: [LoggerService]
})
export class AppModule {}

18. What is @Injectable() decorator?

Answer:
@Injectable():

  • Marks a class as available to be provided and injected

  • Required for services that have their own dependencies

  • Recommended for all services (even without dependencies)

  • providedIn metadata specifies scope ('root', any, platform, etc.)

Implementation:

typescript
Copy
Download
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  constructor(private http: HttpClient) {} // Needs @Injectable to inject HttpClient
  
  getData() {
    return this.http.get('/api/data');
  }
}

19. What are different ways to provide services?

Answer:

  1. Root levelprovidedIn: 'root' (singleton)

  2. Module level: In @NgModule providers array

  3. Component level: In @Component providers array (instance per component)

  4. Lazy-loaded module: Creates separate instance

  5. Platform levelprovidedIn: 'platform'

Implementation:

typescript
Copy
Download
// Root level (preferred)
@Injectable({ providedIn: 'root' })
export class RootService {}

// Module level
@NgModule({
  providers: [ModuleService]
})
export class FeatureModule {}

// Component level
@Component({
  selector: 'app-comp',
  template: `...`,
  providers: [ComponentService] // New instance per component
})
export class MyComponent {}

// Lazy-loaded module
@Injectable()
export class LazyService {}

@NgModule({
  providers: [LazyService]
})
export class LazyModule {}

20. What is hierarchical injector?

Answer:
Angular's DI system is hierarchical:

  • Starts at component level and moves up to root

  • Uses nearest provider in hierarchy

  • Allows different instances at different levels

  • Root injector is at application level

Implementation:

typescript
Copy
Download
// Service with different implementations
@Injectable()
export class ConfigService {
  constructor(public config: string) {}
}

// Root module provides default







No comments:

Post a Comment