Angular Interview
Table of Contents
- What is Angular?
- What is angular CLI?
- What is an Angular Component and how you create a new one?
- What is the interpolation in Angular?
- What is an Angular Directive?
- What is a pipe in Angular?
- Explain events on angular and give examples
- Explain component lifecycle in Angular
- What is the purpose of `ngOnInit()`?
- What is the difference between Constructor() and ngOnInit?
- How do components communicate in Angular?
- What is a module in Angular?
- What is the difference between a component and a module?
- What is Angular Routing?
- What is Lazy Loading in Angular?
- What are services in Angular?
- What is Dependency Injection in Angular?
- What is an Observable in Angular?
- What is the difference between Promise and observable?
- What is AOT compilation?
- What is ng-content in Angular?
- What are Angular guards?
- What is the purpose of `forRoot()` and `forChild()` methods?
- What are Angular decorators?
- What is the difference between `ViewChild` and `ContentChild`?
- What is change detection in Angular?
- What is the purpose of `ngTemplateOutlet`?
- What is the difference between `@ViewChild()` and `@ViewChildren()`?
- What is Angular’s new control flow syntax?
- What is Angular’s defer loading feature?
- What are signals in Angular and how do they differ from RxJS observables?
- What is a Behavior Subject in Angular?
- What is Reactive Programming?
- What is the purpose of `switchMap` operator in RxJS?
- What is the difference between `mergeMap` and `concatMap` in RxJS
- What is the purpose of `catchError` operator in RxJS?
- What is ngrx and why is it used in Angular?
- What are the key concepts of ngrx and how do they work?
- What are the benefits of using NgRx in large-scale applications?
- What is the purpose of the `createFeatureSelector` function in NgRx?
- How do you test NgRx reducers?
- What is the purpose of the `@ngrx/component-store` package?
- Purpose of the createSelector Function in NgRx
- What is the purpose of the `async` pipe?
Some Vanilla JS questions.
- What’s the difference between == and === in JavaScript? When would you use each?
- Explain this in JavaScript and give an example of how it can be used differently in different contexts
- How would you create a deep clone of an object in JavaScript?
- What is the event loop in JavaScript? How does it handle asynchronous tasks?
- What is a debounce function, and when would you use it?
- How do JavaScript modules work? Can you explain import and export?
- What are higher-order functions, and can you provide an example?
- What is the difference between null and undefined? When should you use each?
- Explain currying in JavaScript and give an example
- What is memoization, and how does it work in JavaScript?
What is angular?
Its a front end framework developed and maintained by google. Is used to build Single page applications (SPA), libraries and progressive web apps (PWA).
What is angular CLI?
It’s a command line interface that is used to initialize, develop and maintain angular apps in a faster and efficient way. Its purpose is automate common develop tasks, like component creation, services, modules and the build and execution of the app.
What is an Angular component and how you create a new one?
A component in Angular is a modular piece of the user interface, that encapsulates the logic and the presentation of one specific part of an app. It is created using the command ng generate component followed by the name of the component. Example:
ng generate component <component-name>What is the interpolation in Angular and how you use it in HTML templates?
Is a way to binding the data of the controler to the HTML. It is done using double curly braces `{{value}}`. For example, to show the value of a property `name` in the template of the component, it would be done like this: `{{name}}`.
What is an Angular directive?
An Angular directive is a class that can modify the structure or behavior of the DOM elements in Angular applications. Directives can be categorized into three types:
- Component Directives: Directives that have a template and are used to create reusable components.
- Structural Directives: Directives that change the structure of the DOM by adding or removing elements (e.g.,
*ngIf,*ngFor). - Attribute Directives: Directives that change the appearance or behavior of an existing element, component, or another directive.
What is a pipe in Angular?
A pipe is a way to transform data in your template. It takes in data as input and transforms it to the desired output. For example:
{{ birthday | date:’dd/MM/yyyy’ }}Explain events on Angular and give examples
Angular includes a powerful event handling system that enables to respond to user interactions, such as clicks, keyboard presses, and mouse movements. Here’s an overview of how events operate in Angular.
1. Event Binding
Event binding in Angular is done using the () syntax. You can bind an event to a method in your component class. When the event occurs, the method is called.
<button (click)="onClick()">Click Me</button>In this example, when the button is clicked, the onClick() method in the component class will be executed.
Component Class Example
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html'
})
export class ExampleComponent {
onClick() {
console.log('Button clicked!');
}
}2. Listening to Events
You can listen to various types of events, including:
- Mouse Events:
click,dblclick,mouseenter,mouseleave, etc. - Keyboard Events:
keydown,keyup,keypress, etc. - Focus Events:
focus,blur - Touch Events:
touchstart,touchend - Form Events:
submit,input,change
Example of Listening to Keyboard Events: in the html
<input (keydown)="onKeydown($event)" />In the Component Class Example
onKeydown(event: KeyboardEvent) {
console.log('Key pressed:', event.key);
}3. Passing Event Objects
When binding to an event, you can pass the event object to your handler method. This object contains useful information about the event.
<button (click)="onClick($event)">Click Me</button>In the component class:
onClick(event: MouseEvent) {
console.log('Mouse coordinates:', event.clientX, event.clientY);
}4. Event Modifiers
Angular allows you to use event modifiers to alter the behavior of events. You can manage event propagation and default actions using the $event object.
Preventing Default Behavior
You can prevent the default action of an event by calling event.preventDefault().
html
<form (submit)="onSubmit($event)">
<button type="submit">Submit</button>
</form>Component class
onSubmit(event: Event) {
event.preventDefault(); // Prevents form submission
console.log('Form submitted!');
}5. Template Reference Variables
You can also use template reference variables to access DOM elements and their properties.
html
<input #myInput (keyup)="onKeyup(myInput.value)" />Component class:
onKeyup(value: string) {
console.log('Input value:', value);
}6. Custom Events
You can create custom events within Angular components using EventEmitter. This is particularly useful when creating reusable components that need to communicate with their parent components.
Example: child component
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-child',
template: `<button (click)="notifyParent()">Notify Parent</button>`
})
export class ChildComponent {
@Output() notify = new EventEmitter<string>();
notifyParent() {
this.notify.emit('Hello Parent!');
}
}Example: Parent component (will recieve the output event)
html:
<app-child (notify)="onNotify($event)"></app-child>Component class:
onNotify(message: string) {
console.log('Received from child:', message);
}Explain component lifecycle in Angular:
Each component has a lifecycle that consists of a series of stages from its creation to its destruction. The lifecycle hooks allow you to tap into specific moments of a component’s lifecycle and perform actions accordingly.
Key Stages of the Component Lifecycle
- Creation: The component is initialized and created.
- Update: The component is updated in response to changes in data or inputs.
- Destruction: The component is removed from the view.
Lifecycle Hooks
1. ngOnInit()
- When It’s Called: After the component’s constructor, and right after the first
ngOnChanges(). - Purpose: Initialize component properties, fetch data from services, etc.
2. ngOnChanges()
- When It’s Called: Whenever one or more input properties change.
- Purpose: Respond to changes in input properties.
3. ngDoCheck()
- When It’s Called: During every change detection run.
- Purpose: Implement custom change detection.
5. ngOnDestroy()
- When It’s Called: Just before the component is destroyed.
- Purpose: Cleanup logic, such as unsubscribing from observables or detaching event handlers.
Summary of Lifecycle Hooks
What is the purpose of `ngOnInit()`?
ngOnInit is a lifecycle hook that is called after Angular has initialized all data-bound properties of a directive. It’s used for any additional initialization tasks.
What is the difference between Constructor() and ngOnInit?
The Constructor() is called when the class is instantiated, while ngOnInit is called after the constructor and the bindings have been resolved.
How do components communicate in Angular?
Components in Angular can communicate in various ways:
- Input and Output Properties: Parent to child and child to parent communication.
- ViewChild and ContentChild: Accessing child components directly.
- Service-Based Communication: Sharing data and events between unrelated components using a service
- State Management: NgRx can be used for managing application state and sharing data between components using a centralized store.
1. Input and Output Properties
- Input Properties: Parent components can pass data to child components using
@Input(). - Output Properties: Child components can emit events to notify parent components using
@Output()andEventEmitter.
Example:
Parent Component
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<h1>Parent Component</h1>
<app-child [childData]="data" (notify)="onNotify($event)"></app-child>
`
})
export class ParentComponent {
data = 'Hello from Parent!';
onNotify(message: string) {
console.log('Received from child:', message);
}
}Child Component:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<h2>Child Component</h2>
<p>{{ childData }}</p>
<button (click)="sendNotification()">Notify Parent</button>
`
})
export class ChildComponent {
@Input() childData: string;
@Output() notify = new EventEmitter<string>();
sendNotification() {
this.notify.emit('Hello from Child!');
}
}2. ViewChild and ContentChild
- ViewChild: Allows a parent component to access a child component or directive in its template.
- ContentChild: Used to access a projected content element.
Example:
Parent Component
import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
<h1>Parent Component</h1>
<app-child></app-child>
<button (click)="callChildMethod()">Call Child Method</button>
`
})
export class ParentComponent {
@ViewChild(ChildComponent) child: ChildComponent;
callChildMethod() {
this.child.someMethod(); // Access a method in the child component
}
}3. Service-Based Communication
Services can be used for communication between components that do not have a direct parent-child relationship. This is done using a shared service.
Example:
Shared Service:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private messageSource = new Subject<string>();
currentMessage$ = this.messageSource.asObservable();
changeMessage(message: string) {
this.messageSource.next(message);
}
}Component A:
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-component-a',
template: `<button (click)="sendMessage()">Send Message</button>`
})
export class ComponentA {
constructor(private dataService: DataService) {}
sendMessage() {
this.dataService.changeMessage('Hello from Component A');
}
}Component B:
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-component-b',
template: `<h2>Message: {{ message }}</h2>`
})
export class ComponentB implements OnInit {
message: string;
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.currentMessage$.subscribe(msg => {
this.message = msg;
});
}
}What is a module in Angular?
A module in Angular is a mechanism to group components, directives, pipes, and services that are related, in such a way that can be combined with other modules to create an application.
Key Concepts of Angular Modules
- NgModule: The decorator used to define a module. It takes a metadata object that describes how to compile a component and launch the application.
- Declarations: An array where you declare the components, directives, and pipes that belong to the module.
- Imports: An array of other modules that are required for the functioning of the module. This allows you to use features from other modules.
- Exports: An array of components, directives, or pipes that can be used in the templates of other modules.
- Providers: An array of services that the module will provide to the components.
- Bootstrap: This is used only in the root module and defines the main component that gets bootstrapped when the application starts.
Example of a module:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MyComponent } from './my-component/my-component.component';
@NgModule({
declarations: [
MyComponent // Declare the component that belongs to this module
],
imports: [
CommonModule // Import necessary modules
],
exports: [
MyComponent // Export the component to make it available to other modules
]
})
export class MyModule { }What is the difference between a component and a module?
A component manages a specific section of the user interface (view), while a module serves as a container that groups related components, directives, pipes, and services together.
What is Angular Routing?
Angular routing is a feature that allows you to navigate between different views or components within a single-page application (SPA). It lets you define routes, which are paths that map to specific components. This enables users to move through different parts of your application without needing to reload the page, providing a seamless experience.
Key Concepts of Angular Routing
- RouterModule: This module is responsible for configuring and managing the routes in an Angular application.
- Routes: An array of route objects that define path-component mappings.
- RouterOutlet: A directive that acts as a placeholder where the routed component will be displayed.
- RouterLink: A directive that allows you to create navigation links in your application.
How to use Angular Routing
- Define some routes in a file, this could be the
AppRoutingModule, and then import this file in the app main module:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
const routes: Routes = [
{ path: '', component: HomeComponent }, // Default route
{ path: 'about', component: AboutComponent } // About page route
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }2. Add RouterOutlet
In your main application template (typically app.component.html), add the <router-outlet> directive. This is where the routed components will be displayed.
<nav>
<a routerLink="/">Home</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet> <!-- This is where routed components will appear -->3. Use RouterLink for Navigation
Get Cristian Campos’s stories in your inbox
Join Medium for free to get updates from this writer.
In your HTML, use the routerLink directive to create links for navigation.
<nav>
<a routerLink="/">Home</a>
<a routerLink="/about">About</a>
</nav>What is Lazy Loading in Angular?
Lazy loading is a design pattern used in Angular (and other frameworks) to improve the performance of an application by loading modules only when they are needed, rather than loading everything at the start. This means that if a user never navigates to a certain part of the application, the code for that part will not be loaded, reducing the initial loading time and the amount of data transferred.
Lazy loading is a technique in Angular where you load JavaScript components asynchronously when a specific route is activated. This helps to decrease the startup time of an application.
Why Use Lazy Loading?
- Performance Improvement: It reduces the initial load time of the application by splitting it into smaller chunks.
- Reduced Memory Usage: Only the necessary code is loaded into memory when needed, which can help with performance on low-end devices.
- Better User Experience: Users can interact with the application faster, as they won’t have to wait for all features to load at the beginning.
How to Implement Lazy Loading in Angular
1. Create a New Module
You need to create a module that you want to lazy load. For example, let’s create a FeatureModule: ng generate module feature --route feature --module app.module
2. Set Up Routes in the Feature Module
In the newly created feature-routing.module.ts, you can define the routes for the feature module.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { FeatureComponent } from './feature.component';
const routes: Routes = [
{ path: '', component: FeatureComponent } // Default route for the feature module
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FeatureRoutingModule { }3. Create the Feature Component
You will need to create a component for the feature module: ng generate component feature/feature
4. Configure Lazy Loading in the App Routing Module
In your main routing configuration (usually found in app-routing.module.ts), set up the lazy loading route.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent },
{ path: 'feature', loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule) }, // Lazy loaded route
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }How Lazy Loading Works in this example
When a user navigates to the /feature route, Angular will load the FeatureModule and its associated components. Until that point, the code for the FeatureModule does not get loaded into the application, which improves the initial loading time.
What are services in Angular?
In Angular, services in Angular are a way to define reusable, encapsulated functionality that can be shared across components. They promote a clean architecture by separating business logic from UI logic. By using Angular’s dependency injection, you can easily inject services into components and other services as needed.
Key Features of Services
- Reusable: Services are designed to be reusable across multiple components.
- Singleton: By default, Angular creates a single instance of a service for the entire application, making it easy to share data and functionality.
- Dependency Injection: Services can be injected into components or other services, allowing for a flexible architecture.
Defining a Service:
Here’s an example that fetches a list of items:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root', // Makes the service available throughout the application
})
export class MyService {
getItems() {
return ['Item 1', 'Item 2', 'Item 3']; // Example data
}
}Using a Service in a Component
To use the service in a component, you need to inject it through the constructor.
import { Component, OnInit } from '@angular/core';
import { MyService } from './my-service.service'; // Import the service
@Component({
selector: 'app-my-component',
template: `
<h2>Items</h2>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
`
})
export class MyComponent implements OnInit {
items: string[];
constructor(private myService: MyService) {} // Inject the service
ngOnInit() {
this.items = this.myService.getItems(); // Use the service to get data
}
}What is Dependency Injection in Angular?
Dependency Injection (DI) is a design pattern used in Angular to manage how components and services receive their dependencies. Instead of creating dependencies (like services) directly within a component, DI allows Angular to provide those dependencies when the component is created. This promotes a more modular, testable, and maintainable code structure.
Key Concepts of Dependency Injection
- Dependencies: These are the services or objects that a component needs to function.
- Injector: Angular uses an injector to create instances of services and pass them to components.
- Providers: A provider is a way to configure how a service or dependency is created. You can define providers in the module or at the component level.
How Dependency Injection Works
Here’s a simple explanation of how DI works in Angular:
- Creating a Service: You create a service that contains some functionality.
- Injecting the Service: You declare that a component needs this service by injecting it in the component’s constructor.
- Angular’s Injector: When the component is created, Angular’s injector provides the required service instance to the component.
Benefits of Dependency Injection
- Modularity: Components and services can be developed independently.
- Reusability: Services can be reused across multiple components.
- Testability: You can easily mock services in tests, making components easier to test.
- Maintainability: Changes to the services do not require changes to the components that use them.
What is an Observable in Angular?
An Observable is a way to handle asynchronous data streams in Angular. It is part of the Reactive Programming paradigm and is provided by the RxJS library (Reactive Extensions for JavaScript). Observables help manage events, asynchronous operations, and data flows in a more efficient and flexible manner.
Key Features of Observables
- Asynchronous: Observables allow you to work with data that arrives over time, such as HTTP responses, user input events, or timer events.
- Lazy: Observables do not execute until there is a subscription. This means that no data is emitted until you explicitly subscribe to it.
- Multiple Values: Observables can emit multiple values over time, unlike Promises, which only resolve once.
- Operators: RxJS provides a wide range of operators that can be used to transform, filter, and manage the data emitted by observables.
What is the difference between Promise and observable?
In summary, while both Promise and Observable are used to handle asynchronous operations, they differ significantly in how they manage data streams, execution, cancellation, and error handling. Promises are best suited for single asynchronous events, whereas observables are more powerful for handling multiple values over time and provide a richer set of operators for data manipulation.
What is AOT compilation?
Ahead-of-Time (AOT) compilation converts your Angular HTML and TypeScript code into efficient JavaScript code during the build phase, before the browser downloads and runs that code.
What is ng-content in Angular?
ng-content is a directive in Angular used for content projection. It allows you to create a component that can accept content from its parent component and project that content into the child component's template. This is particularly useful for creating reusable components that can display different content based on the context in which they are used.
What are Angular guards?
Guards in Angular are interfaces which can tell the router whether or not it should allow navigation to a requested route. There are five different types of guards:
- CanActivate
- CanActivateChild
- CanDeactivate
- Resolve
- CanLoad
What is the purpose of `forRoot()` and `forChild()` methods?
- `forRoot()` is used to configure the root module of the application. It’s typically used in the `AppModule`.
- `forChild()` is used in feature modules to register providers without polluting the global injector.
What are Angular decorators?
Decorators are functions that modify JavaScript classes. Angular has many decorators that attach metadata to classes so that it knows what those classes mean and how they should work. Some examples are `@Component()`, `@Injectable()`, `@Input()`, etc.
What is the difference between `ViewChild` and `ContentChild`?
- `ViewChild` gives access to elements in the component’s view (template).
- `ContentChild` gives access to elements that are projected into the component (via `ng-content`).
What is change detection in Angular?
Change detection is the process that allows Angular to keep our views in sync with our models. It works by checking if the model values have changed after various events (like user events, timers, XHR, promises, etc.).
What is the purpose of `TrackBy` in `ngFor` directive?
`TrackBy` is used to track changes in the iterated array. It can improve performance by minimizing DOM operations when items are added or removed.
<li *ngFor=”let item of items; trackBy: trackByFn”>{{item.name}}</li>
trackByFn(index: number, item: any): number {
return item.id;
}What is the purpose of `ngTemplateOutlet`?
`ngTemplateOutlet` is used to insert a template in another template. It’s useful for creating reusable template parts.
What is the difference between `@ViewChild()` and `@ViewChildren()`?
- `@ViewChild()` returns a single element.
- `@ViewChildren()` returns multiple elements as a `QueryList`.
What is Angular’s new control flow syntax?
Angular 17 introduced a new control flow syntax that replaces `*ngIf`, `*ngFor`, and `ngSwitch` with `@if`, `@for`, and `@switch`. This new syntax is more performant and easier to read.
@if (condition) {
<p>Condition is true</p>
} @else {
<p>Condition is false</p>
}
@for (item of items; track item.id) {
<li>{{item.name}}</li>
}
@switch (value) {
@case ('A') { <p>A</p> }
@case ('B') { <p>B</p> }
@default { <p>Other</p> }
}What is Angular’s defer loading feature?
Defer loading is a new feature in Angular 17 that allows you to defer the loading of components or blocks of content until they are needed. This can significantly improve initial load times.
@defer {
<heavy-component />
} @placeholder {
<p>Loading…</p>
}What is Reactive Programming?
Reactive Programming is a programming paradigm focused on the asynchronous data streams and the propagation of changes. It allows you to work with data that changes over time, enabling you to react to those changes in a declarative and efficient way.
Key Concepts of Reactive Programming
- Data Streams: In reactive programming, data is represented as streams, which can be anything that emits values over time, such as user inputs, sensor readings, or HTTP responses.
- Observables: These are the core building blocks in reactive programming. They represent a collection of future values or events, which can be observed and acted upon.
- Subscribers: These are the entities that listen to the data streams (observables) and react whenever new data is emitted.
- Operators: Reactive programming often includes a set of functions (operators) that allow you to transform, combine, filter, and manipulate the data streams in a functional way.
What is a Behavior Subject in Angular?
A Behavior Subject is a type of observable provided by the RxJS library that allows you to maintain a current value and emit it to new subscribers. It is a specialized version of a Subject that requires an initial value and always emits the latest value to subscribers upon subscription.
Key Features of Behavior Subject
- Initial Value: When you create a Behavior Subject, you must provide an initial value. This value is emitted immediately to any new subscribers.
- Latest Value: It holds the latest emitted value, allowing subscribers to receive the most recent update even if they subscribe later.
- Multicast: Like a Subject, a Behavior Subject is multicast, meaning that all subscribers share the same instance and receive the same emitted values.
- Can be Used in Services: Behavior Subjects are commonly used in Angular services to share data between components or manage state.
What are signals in Angular and how do they differ from RxJS observables?
Signals are a new reactive primitive introduced in Angular 14. They are simpler than RxJS observables and are designed for representing values that change over time. Unlike observables, signals are always synchronous and don’t have a completion state.
import { signal } from '@angular/core';
export class MyComponent {
count = signal(0);
increment() {
this.count.update(value => value + 1);
}
}What is the purpose of `switchMap` operator in RxJS?
The switchMap operator in RxJS is used to flatten an observable of observables into a single observable. It switches to a new inner observable every time a new value is emitted by the source observable. The previous inner observable is cancelled and any remaining values are discarded. This is useful in scenarios such as handling user input in real-time search, where you want to cancel the previous search request and start a new one whenever the user enters new input.
import { switchMap } from ‘rxjs/operators’;
searchTerms$.pipe(
switchMap(term => this.searchService.search(term))
).subscribe(results => this.results = results);What is the difference between `mergeMap` and `concatMap` in RxJS
- `mergeMap` subscribes to inner Observables concurrently.
- `concatMap` subscribes to inner Observables sequentially, waiting for each to complete before moving to the next.
What is the purpose of `catchError` operator in RxJS?
`catchError` is used to handle errors in an Observable stream. It catches errors on the source Observable, passing them to a function that returns a new Observable.
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
this.http.get('api/data').pipe(
catchError(error => of([]))
).subscribe(data => this.data = data);What is ngrx and why is it used in Angular?
ngrx is a state management library for Angular that uses the principles of Redux. It helps manage the state of an application by providing a single source of truth for the state and enforcing strict rules for state updates. This makes it easier to manage complex and large-scale applications.
What are the key concepts of ngrx and how do they work?
There are five key concepts in ngrx:
- Actions: represent the facts about “something has happened” in the application, such as user interaction or data received from a server.
Actions are dispatched from components and services to signal state changes. - Reducers: are pure functions that take the current state and an action, and return a new state. They specify how the state changes in response to actions.
- Store: is the central object that holds the current state and provides access to the state. It also allows dispatching actions to trigger state updates.
- Selectors: are pure functions that select slices of the state from the store and return them as observables. They can be used to derive new data from the state, for example to transform or filter data.
- Effects: are used to handle side effects in NgRx applications. They listen for dispatched actions and perform side effects, such as making HTTP requests.
What is the difference between merge and concat in RxJS?
The merge operator in RxJS takes multiple streams and merges them into a single stream, emitting values from each of the streams as soon as they arrive. The concat operator also takes multiple streams, but it concatenates them into a single stream, emitting values from each stream one after the other, only starting with the next stream when the previous one completes.
What are the benefits of using NgRx in large-scale applications?
- Centralized, immutable state management
- Predictable state changes through pure functions
- Powerful dev tools for time-travel debugging
- Scalable architecture for managing complex state interactions
- Clear separation of concerns
- Improved testability
What is the purpose of the `createFeatureSelector` function in NgRx?
createFeatureSelectoris a convenience function that returns a typed selector function for a feature slice of state.
import { createFeatureSelector } from ‘@ngrx/store’;
export const selectFeature = createFeatureSelector<FeatureState>(‘feature’);How do you test NgRx reducers?
Reducers are pure functions, so they can be tested by providing an initial state and an action, and asserting on the returned state.
Example of Testing a Reducer
Let’s say we have a simple counter reducer that increments and decrements a counter based on specific actions.
Counter Reducer (counter.reducer.ts)
import { createReducer, on } from '@ngrx/store';
import { increment, decrement } from './counter.actions';
export const initialState = 0;
const _counterReducer = createReducer(
initialState,
on(increment, state => state + 1),
on(decrement, state => state - 1)
);
export function counterReducer(state, action) {
return _counterReducer(state, action);
}Testing the Counter Reducer (counter.reducer.spec.ts)
import { counterReducer, initialState } from './counter.reducer';
import { increment, decrement } from './counter.actions';
describe('Counter Reducer', () => {
it('should return the default state', () => {
const action = {} as any; // No action provided
const state = counterReducer(undefined, action);
expect(state).toBe(initialState); // Expect the initial state
});
it('should increment the state', () => {
const action = increment(); // Create the increment action
const state = counterReducer(initialState, action);
expect(state).toBe(1); // Expect the state to be incremented
});
it('should decrement the state', () => {
const action = decrement(); // Create the decrement action
const state = counterReducer(1, action); // Start from state 1
expect(state).toBe(0); // Expect the state to be decremented
});
});What is the purpose of the `@ngrx/component-store` package?
`@ngrx/component-store` is a standalone library for managing local component state. It’s useful for managing state that doesn’t need to be shared across the entire application.
Purpose of the createSelector Function in NgRx
The createSelector function in NgRx is a powerful utility used to create memoized selectors for selecting slices of state from the NgRx store. It allows you to define how to derive data from the state and provides a way to efficiently compute values based on the state.
Key Features and Benefits
- Memoization:
createSelectorautomatically caches the results of the selector function. If the input state doesn't change, it returns the cached result instead of recalculating it. This improves performance by avoiding unnecessary computations.
2. Combination:
You can combine multiple selectors together to create more complex selectors. This allows you to build a hierarchy of selectors that can derive data from various parts of the state.
3. Separation of Concerns:
Using selectors helps to separate state selection logic from component logic, making your components cleaner and more focused on presentation.
4. Reactivity:
Selectors can be used with the select operator to create observables in your components, ensuring that the components automatically update when the selected state changes.
What is the purpose of the `async` pipe?
The `async` pipe is used to handle asynchronous data in templates. It allows you to subscribe to observables or promises directly in your Angular templates without the need for manual subscription and unsubscription, thus simplifying the process of working with asynchronous data.
Key Features
- Automatic Subscription:
The async pipe automatically subscribes to the observable or promise when the template is rendered. This means you don’t have to manage subscriptions manually in your component code. - Automatic Unsubscription:
When the component is destroyed, the async pipe automatically unsubscribes from the observable or promise, helping to prevent memory leaks. - Value Extraction:
The async pipe extracts the latest value emitted by the observable or resolved by the promise and makes it available for use in the template. - Simplifies Code:
Using the async pipe reduces boilerplate code in components, as it eliminates the need for separate subscription handling logic.
Example Scenario
Let’s say you have an Angular service that fetches a list of users from an API and returns an observable.
User Service (user.service.ts):
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) {}
getUsers(): Observable<User[]> {
return this.http.get<User[]>('https://api.example.com/users');
}
}Using the async Pipe in a Component
User List Component (user-list.component.ts):
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { UserService } from './user.service';
@Component({
selector: 'app-user-list',
template: `
<h2>User List</h2>
<ul>
<li *ngFor="let user of users$ | async">{{ user.name }}</li>
</ul>
`
})
export class UserListComponent implements OnInit {
users$: Observable<User[]>; // Define an observable property
constructor(private userService: UserService) {}
ngOnInit() {
this.users$ = this.userService.getUsers(); // Assign observable
}
}What is Server-Side Rendering (SSR) in Angular 17?
Refers to the process of rendering Angular applications on the server rather than in the browser. This technique generates HTML content on the server, which is then sent to the client. In Angular, SSR is primarily accomplished using Angular Universal.
Key Benefits of SSR
- Improved Performance:
SSR reduces the time it takes for the initial page to load, as the server sends a fully rendered page to the browser. This minimizes the time users have to wait before they see content on the screen. - Better SEO:
Search engines can index server-rendered pages more effectively, leading to better search engine optimization (SEO). This is particularly important for content-heavy applications where the visibility in search results is crucial. - Faster Time to First Render:
Users see the rendered HTML faster, as there’s no need to wait for JavaScript to load and execute to display content.
Here’s a simplified flow of how SSR works:
- Client Request:
When a user requests a page, the server receives the request. - Server Rendering:
The server uses Angular Universal to render the requested page and generate HTML. - Response:
The server sends the rendered HTML to the client. - Hydration:
The client receives the HTML and Angular’s JavaScript bundles. Angular then takes over (or “hydrates”) the page, making it interactive.
What’s the difference between == and === in JavaScript? When would you use each?
==(loose equality) compares values for equality, allowing for type coercion, so2 == "2"istrue.===(strict equality) compares both value and type, so2 === "2"isfalse.- Use
===when exact type matching is required, which is preferred in most cases to avoid unexpected type coercion.
Explain `this` in JavaScript and give an example of how it can be used differently in different contexts.
- In JavaScript,
thisrefers to the context in which a function is called. For example: - Global scope:
thisrefers to the global object (e.g.,windowin browsers). - Object method:
thisrefers to the object that owns the method. - Arrow functions:
thisis lexically scoped, meaning it inheritsthisfrom the outer function.
const obj = {
name: "The Expert Developer",
getName: function() { return this.name; } // 'this' refers to obj
};
console.log(obj.getName()); // "The Expert Developer"How would you create a deep clone of an object in JavaScript?
- Shallow clone: Using
Object.assign()or the spread operator ({ ...obj }), but it doesn’t clone nested objects. - Deep clone: For a true deep clone, use
JSON.parse(JSON.stringify(obj))(may fail with functions, Dates, etc.) or libraries like Lodash’scloneDeep. - Example:
const obj = { a: { b: 1 } };
const deepClone = JSON.parse(JSON.stringify(obj));What are JavaScript promises, and how do they work? Promise chaining vs. async/await?
- Promises are objects representing eventual completion (or failure) of asynchronous operations.
- Promise chaining uses
.then()and.catch()to handle async operations sequentially. - Async/await provides a more readable, synchronous way to handle asynchronous code.
- Example:
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}What is the event loop in JavaScript? How does it handle asynchronous tasks?
- The event loop is responsible for handling JavaScript’s single-threaded asynchronous behavior. It constantly checks the call stack and task queue.
- Asynchronous tasks (e.g.,
setTimeout, Promises) are queued in the task queue and wait until the call stack is empty before they execute. - This is how JavaScript achieves concurrency without multi-threading.
What is a debounce function, and when would you use it?
- Debounce limits the execution rate of a function. It ensures that a function is only called once after a specified delay.
- Use case: When you want to limit the rate of execution for event listeners, like resize or scroll.
- Example:
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}How do JavaScript modules work? Can you explain import and export?
- JavaScript modules allow you to break up code into reusable, maintainable chunks.
exportis used to make variables, functions, or classes accessible to other modules.importis used to include these exports in other files.- Example:
// module.js
export const greet = () => console.log('Hello');
// main.js
import { greet } from './module.js';
greet(); // HelloWhat are higher-order functions, and can you provide an example?
- Higher-order functions are functions that take other functions as arguments or return them.
- Example:
Array.prototype.mapandfilterare both higher-order functions. - Custom example:
function applyOperation(arr, operation) {
return arr.map(operation);
}
const double = (n) => n * 2;
console.log(applyOperation([1, 2, 3], double)); // [2, 4, 6]What is the difference between null and undefined? When should you use each?
nullis an assignment value, representing the absence of value.undefinedmeans a variable has been declared but not assigned.- When to use:
nullis used intentionally to signify an empty value, whileundefinedoften indicates an uninitialized state.
Explain currying in JavaScript and give an example.
- Currying is the process of breaking down a function that takes multiple arguments into a series of functions that take one argument at a time.
- Example:
function add(a) {
return function(b) {
return a + b;
};
}
const addFive = add(5);
console.log(addFive(3)); // 8What is memoization, and how does it work in JavaScript?
- Answer:
- Memoization is a caching technique that stores function results for specific inputs, speeding up future calls with the same inputs.
- Example:
function memoize(fn) {
const cache = {};
return function(...args) {
const key = JSON.stringify(args);
if (cache[key]) return cache[key];
const result = fn(...args);
cache[key] = result;
return result;
};
}


