interview questions Flashcards

1
Q

-What is angular ?

A

Angular is a component-based framework, built on TypeScript developed by Google . It works by:
Component-Based Architecture: Dividing the UI into reusable components with logic (TypeScript), templates (HTML), and styling (CSS/SCSS).
Data Binding: Synchronizing the view and model using one-way or two-way binding.
Dependency Injection (DI): Providing shared services and managing dependencies efficiently.
Change Detection: Using a mechanism to detect and update the DOM whenever data changes.
RxJS Integration: Managing asynchronous operations with Observables.
Routing: Handling navigation between views.
Compilation: Supporting Ahead-of-Time (AOT) for faster performance or production and Just-in-Time (JIT) for development.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

-How angular works ?

A

The angular framework analysis the angular.json file where we specify the whole configuration for our project.
Then we have the main.ts file which will be the first file to be loaded where we start our angular application and specify the angular App module which is the main module where
we registered our dependencies and modules
Inside the application module we define the routes and the main component in the bootstrap attribute that will be used
After Angular starts running our bootstrap component and all child components that are specified are loaded

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

-Angular pros and cons ?

A

Pros of Angular
Complete Framework:
Angular is a full-fledged framework with built-in tools for routing, state management, HTTP services, and form handling.
Comparison: React and Vue are libraries requiring third-party tools for similar features (e.g., React Router, Vuex).
Two-Way Data Binding:
Angular offers built-in two-way data binding for seamless synchronization between the model and view.
Comparison: React primarily uses one-way data binding, requiring manual updates or state management libraries.
TypeScript Integration:
Angular uses TypeScript, providing strong typing, modern JavaScript features, and better debugging tools.
Comparison: React and Vue rely on JavaScript by default, but TypeScript can be added optionally.
Scalability:
Angular’s modular architecture, dependency injection, and CLI make it suitable for enterprise-scale applications.
Comparison: React and Vue are less opinionated and can require more setup for large projects.

CONS of Angular
Steep Learning Curve:
Angular requires learning concepts like modules, dependency injection, RxJS, and Angular-specific syntax.
Comparison: React and Vue are more beginner-friendly, with simpler concepts and smaller learning curves.
Bundle Size:
Angular has a larger framework size, which can impact performance for small-scale apps.
Comparison: React and Vue generally have smaller library sizes, making them more lightweight.
Complexity for Small Projects: May be overkill for simple or small-scale applications.
RxJS Learning Requirement: Reactive programming with RxJS has a steep learning curve for beginners.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

-What is AOT(Ahead Of Time) compilation ?

A

is a process where the application’s HTML and TypeScript code are compiled into JavaScript code during the build phase, before the application runs in the browser.
Faster Rendering: Since templates are precompiled, the browser can render the application immediately without waiting for runtime compilation.
Smaller Bundle Size: AOT removes Angular decorators and unused code, resulting in a more optimized JavaScript bundle.
Early Error Detection: Syntax and template errors are detected during the build phase, improving code quality and reducing runtime crashes.
Enhanced Security: Templates and components are compiled into JavaScript, making them less vulnerable to injection attacks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

-How AOT Works?

A

-TypeScript into JavaScript.
-Code Generation: Angular generates JavaScript code for templates, change detection…
-Optimization: The final JavaScript is minified and optimized for performance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

-When to Use AOT?

A

-Production Builds: for Angular’s production builds (ng build –prod).
-Large Applications: It ensures faster loading.
-transform everything to javascript before we deploy it to production.

It means in production we have a bunch of javascript files we don’t have any templates and we don’t have any typescript files
ng build –prod

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

-What is just in time compilation ?

A
  • compilation into JavaScript at runtime, in the browser.
  • JIT compiles the application dynamically while it is running.
  • for development mode, as it allows for quick changes without rebuilding the project.
  • Updates in code can be tested immediately without the need for a full compilation step.
  • Increased Bundle Size.
    ng serve
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

JIT VS AOT ?

A

pic

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

When to Use JIT

A

Development Environment: JIT is primarily used during development to enable faster iteration and debugging.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

-What is dependency injections ?

A
  • a design pattern used to implement IoC (Inversion of Control)It allows a class to receive its dependencies from an external source rather than creating them itself
  • DI system enables to inject services into components, other services, or any other class that requires them.
    For example, a component might depend on a service to fetch data.
  • Injector: The mechanism responsible for creating and providing dependencies to Angular components or services.
  • Dependency injection enhances modularity, testability, and maintainability of the code by seperating the creation of dependencies from their usage
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

-How DI Works in Angular ?

A

Declaration: You declare the dependency (e.g., a service) in the @Injectable decorator.
Injection: Use the constructor of a class to inject dependencies. Angular automatically resolves and provides the required dependency using the injector.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

-What are the benefits of DI ?

A
  • Modularity: Promotes separation of concerns by decoupling classes.
  • Reusability:
  • Ease of Maintenance: Centralized configuration of services and dependencies reduces redundancy.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

-What are lifecycles hooks ?

A
  • special methods that handle the lifecycle of components.
  • used to manage component behavior at specific stages, such as initialization, rendering, changes, and destruction

-ngOnInit:
Called once after the component is initialized.

-ngOnChanges:
Called whenever input properties of a component change.

-ngAfterViewInit:
Called once after the component’s view and child views are initialize

-ngOnDestroy:
Called just before the component or directive is destroyed.

-ngDoCheck
Called during every change detection cycle.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Sequence of Execution of lifecycle hooks ?

A

The hooks are executed in the following sequence when a component is created, updated, and destroyed:
ngOnChanges
ngOnInit
ngDoCheck
ngAfterViewInit
ngOnDestroy

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

why NgOnChanges before ngOnInit ?

A

Because it allows the component to detect any changes to inputs immediately upon initialization, before any further setup or initialization logic is executed in ngOnInit.
ngOnInit is called after Angular has set all input properties of the component
When a component is instantiated and has input properties, the framework first sets the inputs (which could trigger ngOnChanges if their values change). Once all the inputs are settled,
Angular will move to ngOnInit to finalize the setup or initialization of the component.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

what is RxJs

A

RxJS (Reactive Extensions for JavaScript)
is a library for working with asynchronous and event-based programming using Observables

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

-What is an observable ?

A
  • is a **core concept from RxJS **that allows asynchronous programming by emitting a stream of values.
  • used for handling asynchronous data like HTTP requests, user input events, and more.
  • Lazy : Observables are lazy, they don’t start emitting values until they are subscribed to.
  • An observable doesn’t do anything until it is subscribed to.
  • A subscription is a listener that reacts to new values emitted by the observable.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

-When to use observables ?

A

HTTP Requests: Angular’s HttpClient service returns an observable, which can be subscribed to get data asynchronously.
Event Handling: Observables can be used to react to DOM events or user interactions.
Reactive Forms: Angular forms use observables to handle changes to form controls or value updates.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

-What is a promise ?

A
  • used to handle asynchronous operations.
  • They represent the completion (or failure) of an asynchronous operation and its resulting value.
  • part of JavaScript and are used to handle operations like HTTP requests or file uploads, where the result is not immediately available.
  • One-time Operation: A Promise is a one-time asynchronous operation. It will resolve (with a value) or reject (with an error) but cannot change after that
    State: A promise can be in one of three states:
    -Pending: The operation is still ongoing.
    -Resolved (Fulfilled): The operation completed successfully, and the promise has a result value.
    -Rejected: The operation failed, and the promise has a reason for failure (typically an error).
  • Chaining: Promises allow you to chain .then() to handle successful completion and .catch() for errors.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

-When to Use Promises in Angular:

A

Use Promises when the operation will complete once and** will only return a single value**, such as one-off HTTP requests or simple asynchronous functions.
For more complex scenarios involving multiple asynchronous events or data streams, Observables are usually preferred.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the difference between observables and promises :

A

-Handling Multiple Values
Promise: A Promise can only return one value — either a result (resolve) or an error (reject). Once the Promise is settled (either fulfilled or rejected), it can’t change.
Observable: An Observable can emit multiple values over time, making it ideal for handling streams of data, such as user inputs, WebSocket messages, or real-time updates.
-Laziness and Execution
Promise: A Promise is eager. It starts executing immediately upon creation, regardless of whether you call .then() or .catch(). Once the Promise is created, it begins its process.
Observable: Observables are lazy. They don’t start emitting values until you subscribe to them. The subscription triggers the execution.
-Cancellation
Promise: Once a Promise is executed, it cannot be cancelled. Even if you no longer need the result, it will continue to run.
Observable: Observables support cancellation. When you unsubscribe from an Observable, it stops emitting further values and can clean up resources like HTTP requests or event listeners
-Chaining
Promise: Promises use .then() for chaining and .catch() for handling errors. You can only chain a single .then() for the result.
Observable: Observables provide more powerful operators through RxJS (such as .map(), .filter(), .mergeMap(), etc.) that allow more complex transformations and handling of streams of data.
-Error Handling
Promise: Errors are handled by the .catch() method, and you can only handle errors once (in the chain of .then()).
Observable: Errors can be handled using .catchError() or in the subscription’s error callback. Since Observables emit multiple values, you can handle errors at any point in the chain, making error management more flexible.
-Use Case Differences
Promise: Suitable for single, one-off asynchronous operations (e.g., HTTP requests).
Observable: Best for situations where multiple values or events need to be emitted over time (e.g., user interactions, real-time data streams).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

-What are streams in Angular ?

A

streams refer to sequences of data that are emitted over time, typically managed using RxJS Observables.
streams in Angular make it easier to work with data that changes over time

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How share data between components ?

A

-Parent to Child (via @Input)
Use the @Input() decorator to pass data from a parent component to its child component.
-Child to Parent (via @Output and EventEmitter)
Use the @Output() decorator and EventEmitter to send data from a child component to its parent.
-via Shared Service and dependency
-@ViewChild(): This allows a parent component to access a reference to a child component or a DOM element inside its template. It enables direct interaction with the child component.
-@ContentChild(): Similar to @ViewChild(), but used for accessing content projected into the component (via ng-content).
- Routing and Navigation
Components can interact with each other through Angular’s Router by navigating between different views. Components are linked via route paths, and data can be passed using route parameters or query parameters.
-Complex state management solution ( NgRx)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

-What is a Component in angular ?

A

Has markup , styling files , and logic(typescript)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
-What is a Directive in angular ?
-is a feature used to add custom behavior to elements in the application **Structural Directives:** Modify the DOM structure by adding, removing, or manipulating elements. *ngIf: Conditionally includes an element in the DOM. *ngFor: Repeats an element for each item in a collection. *ngSwitch: Switches between multiple elements. **Attribute Directives:** Apply specific behavior or styles to existing elements without altering their structure. ngClass: Adds or removes CSS classes dynamically. ngStyle: Updates styles dynamically. * **Custom attribute directives**: Created using the @Directive decorator. Have only typescript file
26
-what is async pipe ?
* is a built-in pipe that simplifies handling asynchronous data, such as data streams provided by Observables or Promises, directly within the template. * no the need for manually subscribing/unsubscribing in the component logic. * useful when working with Angular's reactive forms, HTTP requests, or any real-time data streams, as it streamlines the process of managing asynchronous operations
27
-What is angular IVY ?
Angular Ivy is the default Angular **rendering engine and compiler** introduced in Angular 9. It enhances application performance, reduces bundle size, and provides better debugging tools and ensuring only the necessary parts of Angular are included in the final bundle.
28
-Differences in Use of directive types ?
Structural Directives: Control DOM layout dynamically (e.g., conditional rendering or looping). Attribute Directives: Apply specific behavior or styles to existing elements without altering their structure.
29
-what is the use of constructor in the component ?
special method that is used primarily for initialization purposes DI : The constructor is where Angular injects dependencies (such as services, data models, etc.) into the component It is used to initialize class members or perform any setup needed for the component. It’s not meant for heavy logic but for basic initialization tasks like setting up default values If a component has @Input properties, you can initialize or modify those values in the constructor. Not for Logic: Any logic or actions like API calls or DOM manipulations should be done in ngOnInit() rather than the constructor. The constructor is designed to set up the component, not to execute side effects.
30
-What is untilDestroy ?
* automatically unsubscribe from observables when a component is destroyed. * ensuring that subscriptions are cleaned up without requiring manual unsubscription. export class MyComponent { constructor(private myService: MyService) { myService.getData() .pipe(untilDestroyed(this)) // Automatically unsubscribes on destroy .subscribe(data => console.log(data)); } ngOnDestroy(): void { // No need to manually unsubscribe } }
31
-What is takeUntil ?
takeUntil is an RxJS operator that allows you to automatically unsubscribe from an observable after a certain condition is met
32
-What is OnPush strategy ?
*** checking a component's state only when certain conditions are met** the OnPush change detection strategy is an optimization technique used to improve performance by reducing the number of times Angular checks for changes in the component's data. With the default "Default" change detection strategy, Angular checks all components in the component tree for changes every time any event occurs (like user input, HTTP responses, or timer events). However, with OnPush, Angular will only check the component under certain conditions: Input Changes: When the component's @Input properties change Event Handling: When the component emits an event Manual Change Detection: You can explicitly trigger change detection using ChangeDetectorRef. Observable Updates: If the component is subscribed to an observable (like from RxJS), it will check the component when the observable emits a new value. @Component({ selector: 'app-my-component', changeDetection: ChangeDetectionStrategy.OnPush, // Use OnPush strategy templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponent { @Input() data: any; constructor() { // Component will only be checked when 'data' changes or an event occurs. } }
33
-Limitaions of onPushStrategy ?
-Requires Immutable Data : we must **ensure that objects are replaced (not mutated) to guarantee change detection**. For example, rather than modifying an existing array, a new array must be created and passed to the component. -Event Handling Outside Angular Angular's change detection system relies on Angular-managed events, such as user interactions or HTTP responses. However, if the component’s state is updated by events outside Angular (for example,** WebSocket messages, timers, or other asynchronous operations), OnPush may not trigger the component update.** -Complex debugging : it can also make debugging more challenging. If the component isn't being updated as expected, developers need to ensure that all inputs have new references and that manual change detection is triggered correctly. it needs careful tracking of data mutations.
34
-what are the PROS of the onPush strategy ?
Improved Performance Reduced Change Detection Cycles: OnPush minimizes the number of checks Angular performs. It only checks components when their inputs change or when events occur within them ,t reduces the overhead of constantly checking the entire component tree. Better Memory Management By reducing the number of checks Angular performs, OnPush also reduces the overall memory usage
35
-What is Styling encapsulation :
-Encapsulation: Emulated (default): Styles defined within a component are scoped to that component, using the ::ng-deep selector or attributes like ng-host to scope them. encapsulation:ViewEncapsulation.Emulated -Encapsulation: None: When set to None, Angular does not apply any encapsulation to the component’s styles. This means that the styles defined within the component will apply globally across the entire application, unless otherwise overridden by more specific CSS selectors. the component’s styles will no longer be scoped, and they will apply globally across encapsulation: ViewEncapsulation.None -Encapsulation : ShadowDom fully encapsulate the component's styles. Shadow DOM an isolated DOM for the component, which ensures that styles and markup are completely scoped to the component. encapsulation:ViewEncapsulation.ShadowDom
36
how component styles behave ?
It behaves according to the ViewEncapsulation setting in the component metadata
37
Shadow DOM PROS and CONS ?
Pros of Shadow DOM: -Encapsulation: Provides a high level of encapsulation, preventing external styles and scripts from affecting the component. -Component Reusability: Components created using Shadow DOM are truly isolated, making them easily reusable across different projects without worrying about style conflicts. CONS : Accessibility Concerns: The encapsulation that Shadow DOM provides can interfere with the accessibility of components. Since the shadow tree is hidden from the global document, tools like screen readers may struggle to interact with the component’s content unless specifically handled. Complexity for Developers: The encapsulation provided by Shadow DOM can make it harder to manage certain behaviors, like styles and events. Developers may also find it challenging to apply global styles or to work with other components outside the shadow tree
38
-What are the decators ?
decorators are special types of functions that are used to attach metadata to classes, properties, methods, or parameters Decorators help Angular know how to handle components, services, and other entities within the framework. main types of decorators in Angular: @Component : Marks a class as an Angular component and defines its metadata, such as its template, styles, selector, etc. @Directive : Defines a directive, which is used to modify the behavior of DOM elements. Directives are similar to components but don't have their own templates. @Injectable : Marks a class as available for dependency injection. This is typically used for services, which can then be injected into components or other services. @NgModule : Defines an Angular module, grouping related components, directives, pipes, and services. @HostListener and @HostBinding : Used for listening to events on the host element and binding properties to the host element’s attributes. **HostBinding('value') myValue; is exactly the same as [value]="myValue"** **HostListener('click') myClick(){ } is exactly the same as (click)="myClick()"** PROS : Code Organization: They provide a structured and organized approach to defining components, services, and modules. Reusability: Many Angular decorators (like @Injectable, @Input, etc.) enhance the reusability of components and services.
39
-What are are the change detection strategies ?
Change Detection is the mechanism that tracks changes in the application's state and updates the DOM accordingly. Default Change Detection Strategy: It checks for changes every time any event (like user input or HTTP request completion) triggers Angular's change detection cycle. Pros: It is simple and works well in most scenarios. Cons: It can lead to performance issues in large applications with complex component trees since Angular checks for changes on all components, even if they haven't been affected by the event. OnPush Change Detection Strategy: With this strategy, Angular only checks for changes in the component when one of the following occurs: The component’s input properties change. An event is triggered inside the component (e.g., a user interaction like a button click). An observable that the component subscribes to emits a new value Pros: It improves performance significantly because Angular will only check the component when absolutely necessary (i.e., when input changes or an observable emits). Cons: It requires a more explicit and thoughtful approach to managing component state and change detection, as Angular will no longer automatically detect changes in the component unless these conditions are met. @Component({ selector: 'app-my-component', template: `

{{ data.name }}

`, ** changeDetection: ChangeDetectionStrategy.OnPush, // Enable OnPush **})
40
-How Change Detection Works:
Angular’s default change detection strategy works by traversing the component tree and checking each component’s state to see if anything has changed since the last cycle. This can be computationally expensive, especially in large applications with complex component hierarchies. OnPush reduces the number of checks by only checking components when inputs change or other specific conditions are met. However, developers must be mindful of the conditions that trigger change detection (e.g., immutable data structures or explicit triggers) for OnPush to work effectively. what triggers change detection of a component Angular automatically runs change detection for components, but in some cases, you may want to trigger change detection manually (e.g., after an asynchronous operation or when using OnPush strategy). You can trigger change detection manually using ChangeDetectorRef
41
What is lazy loading ?
is the technique of loading modules only when they are required, instead of loading all the modules at once when the application starts. When implementing lazy loading in Angular, **the application is split into smaller bundles.** only loads when the user navigates to a route that requires them, rather than loading all the code at once. Angular's Router provides an easy way to implement lazy loading using the loadChildren property in route definitions. loadChildren: The loadChildren attribute is used to specify the module to be lazy-loaded when a particular route is accessed. Webpack's Code Splitting: Angular uses Webpack under the hood, which handles code splitting for lazy-loaded modules. This helps to break the application into smaller, more manageable bundles that can be loaded asynchronously. PROS : Reduced Initial Load Time Efficient Resource Use Improved User Experience
42
-What is Preloading Strategy:
Although lazy loading delays the loading of certain modules until required, Angular also provides a mechanism to preload modules for quicker subsequent access using PreloadAllModules or custom preloading strategies. This strategy preloads all lazy-loaded modules after the initial application load. It runs in the background, fetching all modules as soon as the initial load is complete. RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules }) Custom Preloading Strategy: Angular allows developers to create a custom preloading strategy by implementing the PreloadingStrategy interface. This gives more fine-grained control over which modules to preload and when.
43
-When to Use Preloading Strategies:
When you want to improve navigation speed: If your app has several modules that can be loaded later but should be available quickly when the user navigates to them, preloading can help. On larger applications: For big applications with multiple feature modules, preloading can optimize resource usage by keeping the application responsive.
44
-What is Plateform injector?
The Platform Injector is the root injector for an Angular application. It is typically used to provide services that should be available across the entire application, regardless of the module structure. The platform injector is created when the Angular application is initialized Usage: The platform injector is not usually directly accessed by components or modules. It is typically used internally by Angular to manage core services during bootstrapping. he Platform Injector provides a means to access services that may be defined at the application level rather than within a specific module or component context.
45
-What is Module Injector ?
The Module Injector is specific to each NgModule in Angular. It allows services to be injected into components, directives, and other parts of the application that belong to that particular module. has a more limited scope compared to the platform injector. It provides services that are specific to the module in which they are defined. For example, a service defined within the AppModule will only be available to components within that module unless it is specifically exported or provided in another module. ensurs that services are available only to the parts of the app that need them.
46
plateform injector vs Module Injector ?
Scope: Platform Injector is global and available to the entire application. Module Injector is specific to a particular module and its components. Lifecycle: Platform Injector is initialized once when the application starts. Module Injector is initialized when the module is loaded. Examples: Platform Injector: Services like ApplicationRef, NgZone, or other core services that need to be accessible globally are provided at the platform level. Module Injector: Services like HttpClient, custom application services, or state management services are typically scoped within a module.
47
-What is optional decorator ?
The @Optional() decorator in Angular is used in dependency injection (DI) to mark a service or dependency as optional when injecting it into a component or service. When a dependency is marked as optional, Angular will not throw an error if the dependency is not provided To prevent errors when a service or dependency is not provided, but the component can still function without it. export class MyComponent { constructor(@Optional() private myService: MyService) { if (this.myService) { console.log('Service is available'); } else { console.log('Service is not available'); } } } Angular will throw an exception if it cannot find the requested service or dependency in the injector. The exception thrown is an Error : No provider for !
48
-What is the hierarchical injection model for DI ?
When Angular looks up dependencies to inject into a component or service, it follows this logic: Component Injector (Local Injector): it starts by looking in the component’s injector. If the dependency is found, it is injected. If the dependency is not available in the component's injector, Angular continues the lookup process at the parent injector. Parent Injector: This is typically the injector of the parent component, but can also be a service or module that provided the dependency Root Injector: If Angular does not find the dependency in any component or module injector, it finally checks the root injector, which is created when the application starts (often associated with the AppModule).
49
What is the lifecycle of NgRx ?
(Angular's state management library) describes how the state flows and evolves within an Angular application using key concepts like actions, reducers, effects, and selectors Actions : The lifecycle begins when an action is dispatched. Actions are plain JavaScript objects that describe an event or intention to modify the state. Reducers : Once the action is dispatched, it is sent to a reducer. The reducer is a pure function that takes the current state and the dispatched action as inputs, then returns a new state. Stores : The new state returned by the reducer is stored in the NgRx Store. The state is immutable, so NgRx replaces the old state with the new one without directly modifying the original. Selectors : Components and services use selectors to read specific parts of the state from the store. Selectors ensure that only the required slice of the state is accessed. Effects (optional) If an action requires a side effect (e.g., an HTTP call), effects come into play. Effects listen for specific actions, execute asynchronous operations, and then dispatch new actions based on the result. States : The updated state is accessed by Angular components, typically through the store.select() method or using selectors. Components react to state changes and re-render the UI accordingly.
50
-when we should use state managment librairies ?
State management libraries, such as NgRx, Redux, or Akita, are powerful tools for managing application state, particularly in large and complex applications. Complex State Logic Across Multiple Components : When multiple components need to share or synchronize data, state management libraries simplify managing and propagating state changes. Scalability Requirements: Applications with a growing number of features and interdependent components benefit from a centralized and predictable state management approach. Asynchronous Data Handling : Managing API calls, error states, and loading states can become complex. Libraries like NgRx's Effects provide streamlined solutions for such use cases.
51
-pure vs impure pipes ?
pipes are used to transform data in templates Pure Pipes : A pure pipe is only recalculated when Angular detects a change in the input reference. Default Type: All custom pipes are pure by default unless explicitly marked as impure. Usage : Simple and static transformations, like formatting dates, numbers, or strings. Impure Pipes: An impure pipe is recalculated every time Angular's change detection runs, regardless of changes in the input. Reacts to any modification, even within nested properties of objects or arrays. More resource-intensive due to frequent recalculations. How to Create: Set pure: false in the @Pipe decorator. @Pipe({ name: 'impureExamplePipe', pure: false, })
52
-is it good to call methods in the templates?
Methods in the template are invoked every time Angular's change detection runs.=>performance issue Methods can lead to unexpected behaviors when invoked repeatedly. Best Practices : Use Pipes /Move the logic to the component and store the result in a variable/Optimize with OnPush Strategy /optimized using memoization techniques
53
-Memoization Approach in Angular / in components / in pipes ?
Memoization Approach in Angular is a programming optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again. Applying Memoization in Angular Components use libraries like lodash.memoize or write custom memoization functions. Memoized Pipes in Angular Memoized pipes use caching to optimize transformations. They are commonly used to process data within Angular templates. Cache inputs and outputs to avoid recalculating results for the same data.
54
RxJS and its relation with angular ?
**HttpClient**:Angular's HttpClient service returns observables from RxJS to handle HTTP requests. Event Handling : Angular uses observables for **handling DOM events **in components and directives. fromEvent(button, 'click').subscribe(() => console.log('Button clicked!')); Forms and Validation: **Reactive Forms** leverage RxJS observables for value changes and validations. **Routing** : Angular's Router exposes events as observables, enabling developers to listen to navigation changes. this.router.events.subscribe(event => console.log(event)); State Management: ibraries like NgRx heavily rely on RxJS for managing application state and effects.
55
-What are RxJs features ?
Common RxJS Features Used in Angular Operators: Transform data (map, filter). Combine streams (merge, combineLatest). Handle errors (catchError, retry). Subjects: Used for multicasting and sharing a single stream among multiple subscribers. Example: Sharing data between components using a BehaviorSubject. Schedulers: Control how tasks are scheduled and executed (e.g., async, queue).
56
Difference Between Observable and Observer ?
Difference Between Observable and Observer Observable : An observable is a producer of a data stream.It defines how the data stream is created, emitted, and possibly completed or errored. Observables are lazy by nature; they do not execute until subscribed to by an observer. Observer: An observer is a consumer of the data emitted by an observable. It defines the handlers (functions) to process the data, handle errors, or perform an action when the observable completes. The observer must subscribe to the observable to receive updates. Think of an observable as a radio station broadcasting signals, and the observer as a radio tuned in to listen to the station. The signal (data) only reaches the observer when it actively listens (subscribes).
57
hot observables vs cold observables ?
Cold Observables: Observables that start emitting values only when an observer subscribes to them. Each subscriber gets its own independent execution of the observable, meaning the data stream is created separately for each observer. Analogy: Like a personal playlist; each listener starts from the beginning when they press play const coldObservable = new Observable(observer => { console.log('Cold Observable Executed'); observer.next(Math.random()); }); coldObservable.subscribe(val => console.log('Subscriber 1:', val)); coldObservable.subscribe(val => console.log('Subscriber 2:', val)); Output: Different random values for each subscriber. Hot Observables: Observables that start emitting values immediately, regardless of whether there are subscribers. Useful when multiple subscribers should observe the same source of data. Analogy: Like a live radio broadcast; listeners joining later hear only what's currently playing. const subject = new Subject(); const hotObservable = subject.asObservable(); hotObservable.subscribe(val => console.log('Subscriber 1:', val)); subject.next('Hot Observable Executed'); hotObservable.subscribe(val => console.log('Subscriber 2:', val)); subject.next('Another Value');
58
-What are rxjs schedulers ?
is a mechanism to control when and where the execution of observable operations happens. Used to optimize performance and control asynchronous behavior, especially for managing observable streams effectively -asyncScheduler : Executes tasks asynchronously using mechanisms like **setTimeout** -queueScheduler : Synchronously schedules tasks in FIFO order after the current operation completes. -asapScheduler : Executes tasks as soon as possible after the current synchronous code finishes, but before the next event loop. For high-priority tasks that need to be executed before the browser does other work (like rendering). -animationFrameScheduler : Aligns tasks with the browser’s animation frame cycle. PROS : Improve performance / Optimize change detection / Control UI behavior
59
-should we rely on observables in our component ?
relying on observables in Angular components is a good practice, especially when handling asynchronous data (like HTTP requests, user events, or external data streams). Observables provide a powerful, declarative way to manage data flow and state changes,** which aligns well with Angular's reactive programming model.**
60
-What is HttpClient ?
HttpClient in Angular is a service provided by the @angular/common/http module that simplifies making HTTP requests. It is designed to work with the modern Observable API to handle asynchronous data stream supports various HTTP methods such as GET, POST, PUT, DELETE, and PATCH, allowing you to interact with RESTful APIs and other services It automatically parses JSON responses, so you don't have to manually parse the JSON strings returned from an API You can easily catch errors using the catchError operator to manage different HTTP response codes and other issues. Angular allows the use of interceptors with HttpClient to modify requests and responses globally, such as adding authentication tokens, logging, or handling errors globally.
61
-What is fetch?
In Angular, fetch is not the native way of making HTTP requests, as Angular provides the HttpClient service for handling HTTP operations fetch('https://api.example.com/data') .then(response => response.json()) // Parse JSON data .then(data => console.log(data)) // Handle the data .catch(error => console.error('Error:', error)); // Handle errors fetch is a lower-level API, so you would need to manually manage things like headers, parsing JSON, and error handling. fetch returns a Promise, which is easier to use for simpler requests **but less flexible for advanced use cases like chaining multiple asynchronous operations**. fetch does not reject an HTTP error status (like 404 or 500); instead, it resolves the promise and you must manually check the status to handle errors. With fetch, you need to call .json() on the response object to parse the body of the response. While fetch can be used in Angular, HttpClient is recommended for Angular applications as it provides more features that align with the framework's architecture, like observables, built-in error handling, and ease of integration with Angular's dependency injection and other modules.
62
- what is angular interceptor ?
An Angular interceptor is a powerful mechanism that allows you to intercept and modify HTTP requests and responses in your Angular application. It acts as a middleware between the outgoing request and the incoming response. You can use interceptors to manipulate headers, add authentication tokens, log requests, handle errors, or modify the response data before it's returned to the component. Implementation : To create an interceptor, implement the HttpInterceptor interface and define the intercept() method. Seamless Integration/Centralized Logic/Clean Code
63
-if we have multiple interceptor how it will work ?
When you have multiple interceptors in Angular, they will execute in a specific order based on the order in which they are provided in the application's providers array. @NgModule({ providers: [ { provide: HTTP_INTERCEPTORS, useClass: FirstInterceptor, multi: true }, { provide: HTTP_INTERCEPTORS, useClass: SecondInterceptor, multi: true } ] }) export class AppModule {} //FirstInterceptor processes the request first and then forwards it to SecondInterceptor. //When the response comes back, SecondInterceptor processes the response first, followed by FirstInterceptor.
64
what if we have an interceptor but if we want to use http client without it
-Bypassing the Interceptor in Specific Requests by **creating a custom HttpHandler** @Injectable() export class NoInterceptorHttpClient extends HttpClient { constructor(private injector: Injector) { super(injector.get(HttpHandler)); } // Override methods or add custom logic here to avoid using the interceptors } @NgModule({ imports: [HttpClientModule], providers: [ { provide: HttpClient, useClass: NoInterceptorHttpClient } ] }) -Use an Additional Instance of HttpClient Without Interceptors configure a separate HttpClient instance that is not affected by the global interceptors. You can achieve this by creating a new provider for HttpClient in a specific service. export class MyService { constructor(private http: HttpClient) {} getDataWithoutInterceptor() { // Use a custom HttpClient instance that doesn't use interceptors } } -Conditionally Skipping Interceptor Logic intercept(req: HttpRequest, next: HttpHandler) { if (req.headers.has('skip-interceptor')) { // Skip interceptor logic return next.handle(req); } // Otherwise, apply interceptor logic return next.handle(req.clone({ headers: req.headers.set('Authorization', 'Bearer token') })); }
65
techniques of optimization in angular
-Lazy Loading : . Use loadChildren in routes for lazy loading -OnPush Change Detection: Use ChangeDetectionStrategy.OnPush to reduce unnecessary change detection cycle -Avoid Complex Expressions in Templates: Keep template expressions simple. Avoid complex calculations or function calls in templates -Bundle Optimization: Use Angular CLI's production build to optimize bundles -Preload Strategy: For modules that are frequently used, use a preload strategy to load them in the background after the initial load. **-Avoid Memory Leaks: Unsubscribe from observables and event listeners when no longer needed**
66
most common rxjs operators ?
1️⃣ Creation Operators ✅ of() Creates an Observable from static values. ✅ from() Converts arrays, promises, or iterable objects into Observables. ✅ interval() Emits values at fixed time intervals. ✅ timer() Starts emitting after a delay. 2️⃣ Transformation Operators ✅ map() Applies a function to each emitted value. ✅ switchMap() Cancels previous Observable and switches to a new one. 🚀 Best for HTTP Requests to avoid memory leaks! ✅ mergeMap() Flattens Observables but does not cancel previous ones. ✅ concatMap() Processes each Observable in sequence (maintains order). 3️⃣ Filtering Operators ✅ filter() Filters emitted values based on a condition ✅ take(n) Takes only the first n values and then completes. ✅ first() Emits only the first value. 4️⃣ Combination Operators ✅ combineLatest() Combines latest values from multiple Observables. ✅ forkJoin() Waits for all Observables to complete, then emits results once. 🚀 Best for making parallel API calls!
67
var VS let ?
var is function-scoped or global-scoped if declared outside a function, meaning it can be accessed anywhere within the function or globally. let is block-scoped, meaning it’s only available within the nearest block => let is generally preferred over var because it provides better scoping, avoids redeclaration issues, and is safer to use in complex code
68
signals vs RxJS ?
Signals are more straightforward for handling basic state updates without the complexity of RxJS observables. RxJS is best for managing more complex streams, async data, and reactive operations