interview questions Flashcards
-What is angular ?
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 angular works ?
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
-Angular pros and cons ?
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.
-What is AOT(Ahead Of Time) compilation ?
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 AOT Works?
-TypeScript into JavaScript.
-Code Generation: Angular generates JavaScript code for templates, change detection…
-Optimization: The final JavaScript is minified and optimized for performance.
-When to Use AOT?
-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
-What is just in time compilation ?
- 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
JIT VS AOT ?
pic
When to Use JIT
Development Environment: JIT is primarily used during development to enable faster iteration and debugging.
-What is dependency injections ?
- 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 DI Works in Angular ?
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.
-What are the benefits of DI ?
- Modularity: Promotes separation of concerns by decoupling classes.
- Reusability:
- Ease of Maintenance: Centralized configuration of services and dependencies reduces redundancy.
-What are lifecycles hooks ?
- 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.
Sequence of Execution of lifecycle hooks ?
The hooks are executed in the following sequence when a component is created, updated, and destroyed:
ngOnChanges
ngOnInit
ngDoCheck
ngAfterViewInit
ngOnDestroy
why NgOnChanges before ngOnInit ?
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.
what is RxJs
RxJS (Reactive Extensions for JavaScript)
is a library for working with asynchronous and event-based programming using Observables
-What is an observable ?
- 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.
-When to use observables ?
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.
-What is a promise ?
- 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.
-When to Use Promises in Angular:
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.
What is the difference between observables and promises :
-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).
-What are streams in Angular ?
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 share data between components ?
-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)
-What is a Component in angular ?
Has markup , styling files , and logic(typescript)
{{ data.name }}
`, ** changeDetection: ChangeDetectionStrategy.OnPush, // Enable OnPush **})