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 Version | Release Date | Major Features |
|---|---|---|
| Angular 6 | May 2018 | Angular Elements, ng update, ng add, CLI workspaces |
| Angular 7 | Oct 2018 | Virtual scrolling, Drag & Drop, CLI prompts, Angular Material updates |
| Angular 8 | May 2019 | Differential loading, Web Workers, Dynamic imports, Ivy preview |
| Angular 9 | Feb 2020 | Ivy renderer by default, smaller bundles, improved testing |
| Angular 10 | Jun 2020 | New date range picker, stricter types, updated browser support |
| Angular 11 | Nov 2020 | Hot Module Replacement (HMR), faster builds, ESLint support |
| Angular 12 | May 2021 | Ivy everywhere, Webpack 5, Nullish Coalescing (??) support |
| Angular 13 | Nov 2021 | No View Engine, ESBuild, TypeScript 4.4, RxJS 7 |
| Angular 14 | Jun 2022 | Standalone components, typed forms, improved CLI auto-imports |
| Angular 15 | Nov 2022 | Stable standalone APIs, directive composition API, better SSR |
| Angular 16 | May 2023 | Signals (reactivity model), SSR improvements, hydration, standalone stable |
π Detailed Features by Angular Version
πΉ Angular 6
-
Angular Elements: Embed Angular components as custom elements.
-
ng updateandng 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?
You said:
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)
-
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. -
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. -
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. -
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. -
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. -
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). -
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. -
Explain the concept of modules in Angular.
Modules in Angular, defined using the@NgModuledecorator, help organize an application into cohesive blocks of functionality. They group related components, directives, pipes, and services, facilitating code reusability and maintainability. -
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. -
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 likerouterLinkor programmatically via theRouterservice.
⚙️ Intermediate-Level Angular Interview Questions (2–4 Years Experience)
-
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. -
Explain the lifecycle hooks of an Angular component.
Angular components have lifecycle hooks likengOnInit,ngOnChanges,ngDoCheck,ngAfterViewInit, andngOnDestroy, which allow developers to tap into key moments of a component's lifecycle for initialization, change detection, and cleanup. -
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. -
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. -
What are pipes in Angular?
Pipes are functions that transform data in templates. Angular includes built-in pipes likeDatePipe,UpperCasePipe, andCurrencyPipe, and developers can create custom pipes for specific transformations. -
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. -
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. -
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 theloadChildrenproperty and using dynamic imports. -
What are guards in Angular routing?
Guards are interfaces that determine whether navigation to a route should be allowed. Types includeCanActivate,CanDeactivate,Resolve, andCanLoad, each serving different purposes in route protection and data retrieval. -
How do you handle HTTP requests in Angular?
Angular'sHttpClientservice 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)
-
What is the difference between ViewEncapsulation types in Angular?
Angular offers three encapsulation modes:Emulated(default, emulates Shadow DOM),None(no encapsulation), andShadowDom(uses native Shadow DOM). These modes determine how styles are scoped to components. -
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. -
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. -
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. -
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. -
What is the purpose of the
Renderer2service in Angular?
Renderer2is 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. -
Explain the concept of change detection strategies in Angular.
Angular provides two change detection strategies:Default, which checks all components, andOnPush, which checks only when inputs change or events occur, leading to performance optimizations. -
How do you create a custom structural directive in Angular?
A custom structural directive is created by implementing theDirectivedecorator and manipulating the DOM usingTemplateRefandViewContainerRefto add or remove elements based on conditions. -
What is the difference between
ngOnInitand constructor in Angular?
The constructor is used for dependency injection and initializing class members, whilengOnInitis a lifecycle hook called after the component's view has been initialized, suitable for fetching data and other setup tasks. -
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:
-
Top 100 Angular Interview Questions and Answers - FreshersNow
https://www.freshersnow.com/angular-interview-questions-and-answers/
-
Top 100+ Angular Interview Questions & Answers - Intellipaat
https://flexiple.com/angular/interview-questions
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)
| Version | Release Year | Key Features |
|---|---|---|
| Angular 6 | 2018 | - Angular CLI Workspaces - Ivy Renderer (experimental) - RxJS 6 support - Tree-shakable providers |
| Angular 7 | 2018 | - CLI Prompts - Virtual Scrolling (CDK) - Drag & Drop (CDK) - Angular Elements updates |
| Angular 8 | 2019 | - Differential Loading - Ivy Opt-in - Dynamic Imports for Lazy Loading - Web Worker Support |
| Angular 9 | 2020 | - Ivy Renderer (stable) - Smaller Bundle Sizes - Improved AOT Compilation - TypeScript 3.7 Support |
| Angular 10 | 2020 | - CommonJS Import Warnings - New Date Range Picker (Material) - Strict Mode Enhancements |
| Angular 11 | 2020 | - Automatic Font Inlining - Hot Module Replacement (HMR) - Experimental Webpack 5 Support |
| Angular 12 | 2021 | - Nullish Coalescing Support - Stricter Types for Forms - Ivy-Based Language Service |
| Angular 13 | 2021 | - Removal of View Engine - IE11 Support Dropped - Stable APF (Angular Package Format) |
| Angular 14 | 2022 | - Standalone Components (developer preview) - Typed Reactive Forms - Streamlined Page Title API |
| Angular 15 | 2022 | - Stable Standalone APIs - Directive Composition API - Improved Stack Traces |
| Angular 16 | 2023 | - 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:
typescriptCopyDownloadcount = 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:
typescriptCopyDownloadbootstrapApplication(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:
typescriptCopyDownload@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:
jsonCopyDownload"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:
typescriptCopyDownload@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:jsonCopyDownload"builder": "@angular-devkit/build-angular:browser-esbuild"
107.
7. Standalone Project Creation
What: Generate projects without
NgModulesusing:bashCopyDownloadng new --standalone610.
8. RxJS Interop
What: Convert signals to observables and vice versa:
typescriptCopyDownloadcount$ = toObservable(this.count); data = toSignal(this.http.get('...'));
104.
9. DestroyRef & takeUntilDestroyed
What: Simplifies cleanup logic:
typescriptCopyDownloaddestroyRef.onDestroy(() => /* cleanup */); data$ = http.get('...').pipe(takeUntilDestroyed());
47.
10. CSP Support for Inline Styles
What: Adds
ngCspNonceattribute orCSP_NONCEtoken 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:
// 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:
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:
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:
Interpolation:
{{value}}- Displays component value in templateProperty binding:
[property]="value"- Sets element propertyEvent binding:
(event)="handler()"- Listens for eventsTwo-way binding:
[(ngModel)]="property"- Combination of property and event binding
Implementation:
@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:
Component Directives: Components with templates
Structural Directives: Change DOM layout (ngIf, ngFor, ngSwitch)
Attribute Directives: Change appearance/behavior (ngStyle, ngClass)
Implementation:
@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:
ngOnChanges: When input properties change
ngOnInit: After first ngOnChanges
ngDoCheck: During every change detection run
ngAfterContentInit: After content projected
ngAfterContentChecked: After projected content checked
ngAfterViewInit: After component's view initialized
ngAfterViewChecked: After component's view checked
ngOnDestroy: Before component is destroyed
Implementation:
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:
Emulated (default): Styles are scoped to component
None: Styles are global
ShadowDom: Uses browser's shadow DOM
Implementation:
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:
Parent to Child: Using @Input()
Child to Parent: Using @Output() and EventEmitter
Sibling Components: Via parent or using a service
Unrelated Components: Using services or state management
Implementation:
// 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:
@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:
// 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:
Create a class with directive logic
Decorate with @Directive
Define selector (CSS selector)
Optionally inject ElementRef to access host element
Implementation:
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:
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:
Create a class implementing PipeTransform
Decorate with @Pipe
Implement transform method
Implementation:
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:
@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:
@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:
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:
// 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:
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:
Root level:
providedIn: 'root'(singleton)Module level: In @NgModule providers array
Component level: In @Component providers array (instance per component)
Lazy-loaded module: Creates separate instance
Platform level:
providedIn: 'platform'
Implementation:
// 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:
// Service with different implementations @Injectable() export class ConfigService { constructor(public config: string) {} } // Root module provides default
No comments:
Post a Comment