Top Angular Interview Questions & Answers
What is Angular?
- Angular is a popular open-source framework for building client-side web applications.
- It is maintained by Google.
- It provides a structured approach to developing dynamic single-page applications (SPAs).
What are the key building blocks of an Angular application?
- Components
- Modules
- Templates
- Data Binding
- Directives
- Services
- Dependency Injection
- Routing
- CLI (Command Line Interface)
What is a Component in Angular?
- Components are the fundamental building blocks of Angular applications.
- Each component controls a patch of the screen called a view.
- They consist of a TypeScript class, an HTML template, and CSS styles.
Example:
import { Component } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.css']
})
export class MyComponent {
// Component logic
}
What is a Module in Angular?
- Modules are containers for a cohesive block of functionality.
- They group related components, directives, pipes, and services.
- Every Angular application has at least one root module, typically named
AppModule
.
Example:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
What is the purpose of NgModule
metadata?
NgModule
metadata describes how to compile a component's template and how to create an injector at runtime.- It declares the components, directives, and pipes that belong to the module.
- It imports other modules whose exported classes are needed by component templates declared in this module.
- It lists the providers for services used by the module.
- It identifies the root component that Angular should bootstrap.
What is the difference between AngularJS and Angular?
- AngularJS is the original version (1.x), while Angular (2+) is a complete rewrite.
- Angular uses TypeScript, while AngularJS uses JavaScript.
- Angular has a component-based architecture, while AngularJS uses controllers and scopes.
- Angular has better performance and is more mobile-friendly.
- Angular has a more powerful CLI and better tooling.
What is Data Binding in Angular?
- Data binding is a mechanism that synchronizes data between the component class and the HTML template.
- It allows you to display component data in the view and respond to user input.
What are the different types of Data Binding in Angular?
- Interpolation: One-way data binding from component to view (
{{ value }}
). - Property Binding: One-way data binding from component to view (
[property]="value"
). - Event Binding: One-way data binding from view to component (
(event)="handler()"
). - Two-Way Data Binding: Synchronizes data between component and view (
[(ngModel)]="value"
).
Explain Interpolation.
- Interpolation is a one-way data binding technique that displays component data in the template.
- It uses double curly braces
{{ }}
to embed expressions within the HTML.
Example:
{{ pageTitle }}
Explain Property Binding.
- Property binding is a one-way data binding technique that sets the value of an HTML element's property to a component property.
- It uses square brackets
[]
around the target property.
Example:
Explain Event Binding.
- Event binding is a one-way data binding technique that allows you to respond to events triggered by the user in the template (e.g., button clicks, input changes).
- It uses parentheses
()
around the target event.
Example:
Explain Two-Way Data Binding.
- Two-way data binding combines property binding and event binding to synchronize data between the component and the view in both directions.
- It is commonly used with form elements using the
ngModel
directive. - It requires importing the
FormsModule
.
Example:
Hello, {{ userName }}
What are Directives in Angular?
- Directives are classes that add behavior to elements in your application.
- They modify the DOM (Document Object Model).
What are the different types of Directives?
- Component Directives: Directives with a template (the most common type).
- Structural Directives: Directives that change the DOM layout by adding, removing, or manipulating elements (e.g.,
*ngIf
,*ngFor
,*ngSwitch
). - Attribute Directives: Directives that change the appearance or behavior of an element, component, or another directive (e.g.,
ngStyle
,ngClass
).
Explain *ngIf
directive.
*ngIf
is a structural directive that conditionally adds or removes an element from the DOM based on a boolean expression.
Example:
This message is shown.
Explain *ngFor
directive.
*ngFor
is a structural directive that repeats a template for each item in a collection (e.g., an array).
Example:
- {{ item }}
Explain *ngSwitch
directive.
*ngSwitch
is a structural directive that displays one of several possible elements based on a switch value.- It works with
*ngSwitchCase
and*ngSwitchDefault
.
Example:
Loading...
Data loaded successfully.
Unknown status.
Explain ngClass
directive.
ngClass
is an attribute directive that dynamically adds or removes CSS classes from an element.- It can take a string, an array of strings, or an object where keys are class names and values are boolean expressions.
Example:
Styled Text
Explain ngStyle
directive.
ngStyle
is an attribute directive that dynamically sets inline CSS styles on an element.- It takes an object where keys are style properties and values are the style values.
Example:
Styled Text
What is a Service in Angular?
- A service is a class with a specific purpose, typically to provide data or functionality to components.
- Services are often used for business logic, data fetching, and sharing data between components.
- They are typically marked with the
@Injectable()
decorator.
Example:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' // Makes the service a singleton
})
export class DataService {
getData() {
return ['item1', 'item2'];
}
}
What is Dependency Injection?
- Dependency Injection (DI) is a design pattern where a class receives its dependencies from external sources rather than creating them itself.
- Angular's DI system provides instances of services to components and other services.
- This promotes reusability, testability, and maintainability.
How do you inject a Service into a Component?
- You inject a service into a component by declaring it as a parameter in the component's constructor.
Example:
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.css']
})
export class MyComponent {
data: string[];
constructor(private dataService: DataService) {
this.data = this.dataService.getData();
}
}
What is a Pipe in Angular?
- A Pipe is a class that transforms data for display in a template.
- They are used to format data such as dates, currency, and text.
- Angular provides built-in pipes (e.g.,
DatePipe
,CurrencyPipe
,UpperCasePipe
,LowerCasePipe
,DecimalPipe
). - You can also create custom pipes.
Example of using a built-in pipe:
{{ currentDate | date:'mediumDate' }}
{{ price | currency:'USD' }}
How are Pipes used in templates?
- Pipes are used in template expressions using the pipe symbol (
|
). - They take the data as input and return the transformed data.
- Multiple pipes can be chained together.
Example:
{{ 'hello world' | uppercase | slice:0:5 }}
What is Routing in Angular?
- Routing in Angular allows you to navigate between different views (components) in your application based on the URL.
- It enables the creation of single-page applications with multiple "pages".
- The
@angular/router
module provides the necessary functionality.
How do you configure Routing?
- You define routes in an array of
Route
objects, typically in an application-level routing module. - Each
Route
object maps a URL path to a component. - You use the
directive in your main application template to mark where the routed components should be displayed.
Example:
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 },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
What is Angular CLI?
- The Angular CLI (Command Line Interface) is a powerful tool for developing Angular applications.
- It provides commands to create projects, components, services, modules, and more.
- It also handles building, testing, and deploying applications.
Example commands:
ng new my-app
ng generate component my-component
ng serve
ng build --prod
What are Decorators in Angular?
- A decorator is a special kind of declaration that can be attached to classes, methods, accessors, properties, or parameters.
- Decorators provide a way to add metadata to code and modify its behavior.
- Angular uses decorators extensively (e.g.,
@Component()
,@NgModule()
,@Injectable()
).
Explain @Input()
decorator.
@Input()
is a decorator used to define an input property on a child component.- It allows a parent component to pass data to its child component.
Example:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: '{{ message }}
'
})
export class ChildComponent {
@Input() message: string;
}
Explain @Output()
decorator.
@Output()
is a decorator used to define an output property on a child component.- It allows a child component to emit events to its parent component.
- It is typically used with
EventEmitter
.
Example:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: ''
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter();
sendMessage() {
this.messageEvent.emit('Hello from child!');
}
}
What are Lifecycle Hooks in Angular?
- Lifecycle hooks are special methods that Angular calls at specific points in the lifecycle of a component or directive.
- They allow you to perform actions at these key moments (e.g., initialization, change detection, destruction).
Name some common Lifecycle Hooks.
ngOnChanges
: Called when input property values change.ngOnInit
: Called once after the component is initialized.ngDoCheck
: Called during every change detection run.ngAfterContentInit
: Called after Angular projects external content into the component's view.ngAfterContentChecked
: Called after Angular checks the content projected into the component.ngAfterViewInit
: Called after Angular initializes the component's views and child views.ngAfterViewChecked
: Called after Angular checks the component's views and child views.ngOnDestroy
: Called just before Angular destroys the component.
Explain the difference between ngOnInit
and the constructor.
- The constructor is a standard TypeScript feature used to initialize class members and inject dependencies.
ngOnInit
is an Angular lifecycle hook called after the component's data-bound input properties are initialized.- It's generally recommended to perform initialization logic that depends on input properties or external data fetching within
ngOnInit
, while the constructor is for basic setup and dependency injection.
What is Change Detection in Angular?
- Change detection is the mechanism by which Angular updates the DOM to reflect the current state of the application.
- It checks for changes in data properties and updates the view accordingly.
What are the different Change Detection Strategies?
- Default (
ChangeDetectionStrategy.Default
): Angular checks all components from top to bottom every time an event occurs or asynchronous operation completes. -
OnPush (
ChangeDetectionStrategy.OnPush
): Angular only checks the component and its subtree when:- An input property changes.
- An event is emitted by the component or one of its children.
- Change detection is explicitly triggered.
- An observable the component is subscribed to emits a new value (when using the
async
pipe).
When would you use ChangeDetectionStrategy.OnPush
?
- You would use
OnPush
to improve performance by reducing the number of checks Angular needs to perform. - It's suitable for components that primarily rely on input properties for their data and don't have many internal state changes triggered by events within the component itself.
What are Templates in Angular?
- Templates are HTML fragments that define the structure and layout of a component's view.
- They can contain standard HTML, Angular template syntax (interpolation, directives, data binding), and other components.
How can you define a component's template?
- Inline Template: Using the
template
property in the@Component()
decorator. - External Template: Using the
templateUrl
property to link to an HTML file.
Inline Example:
@Component({
selector: 'app-my-component',
template: 'This is an inline template.
'
})
export class MyComponent { }
External Example:
@Component({
selector: 'app-my-component',
templateUrl: './my-component.html'
})
export class MyComponent { }
What is Template Reference Variable?
- A template reference variable is a variable you declare in a template to refer to an element, component, or directive.
- It's denoted by a hash symbol (
#
) followed by the variable name. - You can use it to access properties and methods of the referenced element or component.
Example:
What is the difference between a Component and a Directive?
- Component: Has a template and controls a view. It's the main building block of the UI.
- Directive: Doesn't have a template. It modifies the behavior or appearance of existing elements, components, or directives.
What is the purpose of @Injectable()
decorator?
- The
@Injectable()
decorator marks a class as a service that can be injected into other classes. - It's necessary for Angular's dependency injection system to provide instances of the service.
- The
providedIn: 'root'
option makes the service a singleton available throughout the application.
What is the difference between a Service and a Component?
- Service: Focuses on providing data or functionality. It doesn't have a UI.
- Component: Focuses on the UI and interacts with services to get data and perform actions.
What is the role of the providers
array in @NgModule
?
- The
providers
array lists the services that the module makes available for dependency injection. - When a service is listed in the
providers
array of a module, Angular creates a single instance of that service that can be injected into components and services declared within that module.
What is the role of the declarations
array in @NgModule
?
- The
declarations
array lists the components, directives, and pipes that belong to this module. - Only components, directives, and pipes that are declared within a module can be used within that module's templates.
What is the role of the imports
array in @NgModule
?
- The
imports
array lists other modules whose exported classes (components, directives, pipes) are needed by component templates declared in this module. - For example, if you use
*ngIf
or*ngFor
in your component templates, you need to importCommonModule
(orBrowserModule
in the root module).
What is the role of the exports
array in @NgModule
?
- The
exports
array lists the components, directives, and pipes that are declared in this module and should be available for use in templates of components declared in other modules that import this module. - Components, directives, and pipes declared in a module are private by default unless explicitly exported.
What is the purpose of bootstrap
array in @NgModule
?
- The
bootstrap
array is used only in the root module (AppModule
). - It identifies the root component that Angular should bootstrap when the application starts.
- This component is the entry point of the application's UI.
What are Observables in Angular?
- Observables are a way to handle asynchronous operations and streams of data.
- They are part of the RxJS library, which is commonly used with Angular.
- Observables can emit multiple values over time.
- They are used extensively in Angular for handling HTTP requests, events, and more.
What is the difference between Observables and Promises?
-
Promises:
- Handle a single asynchronous event.
- Are eager (start executing immediately when created).
- Cannot be cancelled.
-
Observables:
- Handle multiple asynchronous events over time.
- Are lazy (don't start executing until subscribed to).
- Can be cancelled.
- Provide a rich set of operators for transforming and manipulating data streams.
What is the async
pipe?
- The
async
pipe is a built-in Angular pipe that automatically subscribes to an Observable or Promise and returns the latest emitted value. - When the component is destroyed, the
async
pipe automatically unsubscribes, preventing memory leaks.
Example:
{{ data$ | async }}
How do you handle HTTP requests in Angular?
- You use the
HttpClient
service, which is part of the@angular/common/http
module. HttpClient
methods (get
,post
,put
,delete
, etc.) return Observables.- You subscribe to these Observables to get the response data.
Example:
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient) { }
getData() {
this.http.get('/api/data').subscribe(data => {
console.log(data);
});
}
What is an Interceptor in Angular?
- An HTTP Interceptor is a class that intercepts HTTP requests and responses.
- You can use interceptors to modify requests (e.g., add authentication headers) or responses (e.g., handle errors).
- Interceptors are useful for implementing cross-cutting concerns like authentication, logging, and error handling.
How do you create a custom Pipe?
- You create a class that implements the
PipeTransform
interface. - You define a
transform
method that takes the input value and optional arguments and returns the transformed value. - You apply the
@Pipe()
decorator to the class, providing a name for the pipe. - You declare the pipe in the
declarations
array of your module.
Example:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverseString'
})
export class ReverseStringPipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
What is the difference between a Pure Pipe and an Impure Pipe?
-
Pure Pipe:
- Angular executes a pure pipe only when it detects a pure change to the input value.
- A pure change is a change to a primitive input value (
string
,number
,boolean
,symbol
) or a changed object reference (Date
,Array
,Object
). - Pure pipes are more performant.
-
Impure Pipe:
- Angular executes an impure pipe during every change detection cycle, regardless of whether the input value has changed.
- Impure pipes are less performant and should be used with caution.
- Examples include pipes that mutate objects or arrays.
What is the purpose of the zone.js
library in Angular?
zone.js
is a library that patches asynchronous browser APIs (likesetTimeout
,setInterval
, event listeners, XHR).- It creates "zones" which provide a context for asynchronous operations.
- Angular uses
zone.js
to detect when asynchronous operations complete, triggering change detection.
What is Ahead-of-Time (AOT) Compilation?
- AOT compilation is a build process that compiles your Angular application's code into native JavaScript before the browser loads it.
- Benefits include faster rendering, smaller application size, and better error detection during the build process.
What is Just-in-Time (JIT) Compilation?
- JIT compilation is the default compilation method in development.
- It compiles your Angular application's code in the browser at runtime.
- This is faster for development but results in larger application size and slower initial rendering in production.
What is the difference between AOT and JIT compilation?
- AOT: Compiles at build time (before the browser). Faster runtime performance, smaller bundles, build-time error checking. Used for production builds.
- JIT: Compiles at runtime (in the browser). Faster development cycles, larger bundles, runtime error checking. Used for development builds.
How do you enable AOT compilation?
- You enable AOT compilation using the Angular CLI with the
--prod
flag during the build process:ng build --prod
.
What is Lazy Loading?
- Lazy loading is a technique where modules are loaded only when they are needed (e.g., when a user navigates to a specific route).
- This improves the initial loading time of the application by reducing the size of the initial bundle.
How do you implement Lazy Loading in Angular?
- You define a route that uses the
loadChildren
property to specify the path to the module to be lazy loaded. - The module to be lazy loaded should be defined with its own routing module.
Example:
// In app-routing.module.ts
const routes: Routes = [
{ path: 'lazy', loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule) }
];
What are Guards in Angular Routing?
- Route guards are interfaces that you can implement to control access to routes.
- They allow you to determine whether a user can navigate to a route, leave a route, or load a lazy-loaded module.
Name some common Route Guards.
CanActivate
: Determines if a user can activate a route.CanActivateChild
: Determines if a user can activate a child route.CanDeactivate
: Determines if a user can leave a route.CanLoad
: Determines if a user can load a lazy-loaded module.Resolve
: Prefetches data before the route is activated.
Explain CanActivate
guard.
- The
CanActivate
guard is an interface with acanActivate()
method. - The
canActivate()
method returns a boolean, an Observable, or a Promise . - If it returns
true
, navigation is allowed; otherwise, it's blocked. - It's commonly used for authentication and authorization.
What is Parameterized Routing?
- Parameterized routing allows you to pass data as part of the URL segments.
- You define route parameters in the route configuration using a colon (
:
). - You can access the route parameters in the component using the
ActivatedRoute
service.
Example Route Configuration:
const routes: Routes = [
{ path: 'product/:id', component: ProductDetailComponent }
];
Accessing Parameter in Component:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {
this.route.params.subscribe(params => {
const productId = params['id'];
// Use productId to fetch data
});
}
What are Query Parameters?
- Query parameters are optional key-value pairs appended to the URL after a question mark (
?
). - They are used to pass optional data to a route without changing the route path itself.
- You access query parameters using the
ActivatedRoute
service.
Example URL: /products?category=electronics&sort=price
Accessing Query Parameters in Component:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {
this.route.queryParams.subscribe(params => {
const category = params['category'];
const sort = params['sort'];
// Use query parameters
});
}
What is the difference between Route Parameters and Query Parameters?
-
Route Parameters:
- Part of the URL path.
- Used for essential data that identifies a specific resource (e.g., user ID, product ID).
- Required for the route to match.
-
Query Parameters:
- Appended to the URL after
?
. - Used for optional data or filtering/sorting information.
- Not required for the route to match.
- Appended to the URL after
What is the purpose of the RouterModule.forRoot()
and RouterModule.forChild()
?
RouterModule.forRoot(routes)
: Used in the root module (AppModule
) to configure the main application routes and set up the router service. It registers the router providers at the root level.RouterModule.forChild(routes)
: Used in feature modules (lazy-loaded modules) to define their own routes. It registers the router providers specific to that feature module without creating new instances of root-level services.
What is View Encapsulation?
- View encapsulation determines how the component's CSS styles affect the rest of the application.
- Angular provides different encapsulation strategies.
What are the different View Encapsulation strategies?
- Emulated (Default): Angular adds unique attributes to component elements and scopes CSS rules to those attributes, simulating shadow DOM.
- ShadowDom: Angular uses the browser's native Shadow DOM implementation to isolate component styles.
- None: Angular does not apply any encapsulation. Component styles become global and can affect other parts of the application.
Explain ViewEncapsulation.Emulated
.
- This is the default strategy.
- Angular transforms component CSS rules to apply only to the component's view by adding a unique attribute to the host element and prefixing CSS selectors with that attribute.
- Example: A component with selector `app-my-component` might get a `_ngcontent-c0` attribute, and its CSS rules will be modified to target elements with that attribute.
Explain ViewEncapsulation.ShadowDom
.
- This strategy uses the browser's native Shadow DOM API.
- The component's template is rendered within a Shadow DOM tree, and its styles are completely isolated from the main document's styles.
- This provides strong encapsulation but has browser support considerations.
Explain ViewEncapsulation.None
.
- In this strategy, the component's styles are added to the global styles of the application.
- There is no style isolation, and the component's CSS rules can affect any element in the application.
- This is generally not recommended unless you have a specific reason to make styles global.
How do you configure View Encapsulation for a component?
- You set the
encapsulation
property in the@Component()
decorator.
Example:
import { Component, ViewEncapsulation } from '@angular/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.html',
styleUrls: ['./my-component.css'],
encapsulation: ViewEncapsulation.None // Or Emulated, ShadowDom
})
export class MyComponent { }
What is the difference between a Module and a Component?
- Module: A container that groups related components, directives, pipes, and services. It defines how different parts of the application work together.
- Component: A building block that controls a part of the UI and has a template.
What is the purpose of the HttpClientModule
?
HttpClientModule
provides theHttpClient
service, which is used for making HTTP requests.- You need to import
HttpClientModule
into yourAppModule
(or a feature module that uses HTTP) to use theHttpClient
service.
What is the purpose of the FormsModule
?
FormsModule
provides support for template-driven forms, including thengModel
directive for two-way data binding.- You need to import
FormsModule
into your module to use template-driven forms.
What is the purpose of the ReactiveFormsModule
?
ReactiveFormsModule
provides support for reactive forms, which are a more robust and scalable way to handle forms in Angular.- Reactive forms are built programmatically in the component class.
- You need to import
ReactiveFormsModule
into your module to use reactive forms.
What is the difference between Template-Driven Forms and Reactive Forms?
-
Template-Driven Forms:
- Logic is primarily in the template using directives like
ngModel
. - Easier for simple forms.
- Less control and testability.
- Logic is primarily in the template using directives like
-
Reactive Forms:
- Logic is primarily in the component class using
FormGroup
,FormControl
, andFormArray
. - More scalable and testable.
- Better for complex forms and dynamic form generation.
- Logic is primarily in the component class using
How do you create a Reactive Form?
- You import
ReactiveFormsModule
into your module. - In the component class, you create a
FormGroup
orFormBuilder
instance. - You define
FormControl
instances for each form input and group them within aFormGroup
. - You bind the
FormGroup
to the form element in the template using the[formGroup]
directive and bindFormControl
instances to input elements using theformControlName
directive.
Example (Component):
import { Component } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
templateUrl: './reactive-form.html'
})
export class ReactiveFormComponent {
myForm = new FormGroup({
name: new FormControl(''),
email: new FormControl('')
});
onSubmit() {
console.log(this.myForm.value);
}
}
Example (Template):
What is FormBuilder
?
FormBuilder
is a helper service that provides a convenient way to createFormGroup
,FormControl
, andFormArray
instances in reactive forms.- It reduces boilerplate code.
Example using FormBuilder
:
import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
templateUrl: './reactive-form.html'
})
export class ReactiveFormComponent {
myForm = this.fb.group({
name: [''],
email: ['']
});
constructor(private fb: FormBuilder) { }
onSubmit() {
console.log(this.myForm.value);
}
}
How do you add validation to Reactive Forms?
- You add validators to the
FormControl
instances when creating them. - Angular provides built-in validators (e.g.,
Validators.required
,Validators.minLength
,Validators.maxLength
,Validators.email
). - You can also create custom validators.
Example:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
templateUrl: './reactive-form.html'
})
export class ReactiveFormComponent {
myForm = new FormGroup({
name: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email])
});
onSubmit() {
console.log(this.myForm.value);
}
}
How do you display validation error messages in Reactive Forms?
- You can access the validation status of a
FormControl
using its properties likevalid
,invalid
,touched
,dirty
, anderrors
. - You can use structural directives like
*ngIf
to conditionally display error messages based on these properties.
Example:
What is the purpose of trackBy
in *ngFor
?
trackBy
is a function used with*ngFor
to help Angular track changes to items in a collection.- Without
trackBy
, if you modify an item in the collection, Angular rerenders the entire list. - With
trackBy
, Angular can identify which items have changed and only update the corresponding DOM elements, improving performance, especially for large lists.
Example:
trackById(index: number, item: any): number {
return item.id; // Assuming items have an 'id' property
}
- {{ item.name }}
What is the difference between ViewChild
and ContentChild
?
ViewChild
: Used to query for an element, component, or directive within the component's *own* view (defined in its template).ContentChild
: Used to query for an element, component, or directive projected into the component's view from *external* content using
.
Explain ViewChild
.
@ViewChild()
is a decorator used to access a child element, component, or directive from the component's TypeScript class.- It takes a selector (e.g., a template reference variable or component type) as an argument.
- The element is available in the
ngAfterViewInit
lifecycle hook.
Example:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-parent',
template: ''
})
export class ParentComponent implements AfterViewInit {
@ViewChild('myInput') myInput: ElementRef;
ngAfterViewInit() {
this.myInput.nativeElement.focus();
}
}
Explain ContentChild
.
@ContentChild()
is a decorator used to access projected content within the component's TypeScript class.- It takes a selector (e.g., a component type or directive) as an argument.
- The projected content is available in the
ngAfterContentInit
lifecycle hook.
Example (Parent Component Template):
This is projected content.
Example (Child Component):
import { Component, ContentChild, ElementRef, AfterContentInit } from '@angular/core';
@Component({
selector: 'app-child',
template: ' '
})
export class ChildComponent implements AfterContentInit {
@ContentChild('projectedParagraph') projectedParagraph: ElementRef;
ngAfterContentInit() {
console.log(this.projectedParagraph.nativeElement.textContent);
}
}
What is the purpose of
?
is used in a component's template to define a placeholder where content from the parent component can be projected.- This is a mechanism for content projection, allowing a component to receive and display content provided by its parent.
What is Content Projection?
- Content projection is a design pattern where a component includes content provided by its parent component within its own template.
- It allows for more flexible and reusable components.
- It's implemented using the
element.
What is the difference between ViewChildren
and ContentChildren
?
ViewChildren
: Used to query for multiple elements, components, or directives within the component's *own* view. Returns aQueryList
.ContentChildren
: Used to query for multiple elements, components, or directives projected into the component's view from *external* content. Returns aQueryList
.
What is QueryList
?
QueryList
is a collection type returned by@ViewChildren()
and@ContentChildren()
.- It is a list of items queried from the DOM.
- It is observable, meaning you can subscribe to changes in the list.
What is the purpose of the Renderer2
service?
Renderer2
is an abstract class that provides a low-level API for interacting with the DOM.- It abstracts away the underlying rendering layer (e.g., browser DOM, server-side rendering).
- It's recommended to use
Renderer2
instead of directly manipulating the DOM when working with Angular to ensure your application can run in different environments (like server-side rendering).
When should you use Renderer2
instead of direct DOM manipulation?
- Use
Renderer2
when you need to manipulate the DOM in a way that is independent of the rendering environment. - Direct DOM manipulation can break server-side rendering and other rendering platforms.
What is Server-Side Rendering (SSR) in Angular?
- SSR is the process of rendering Angular components on the server and sending the static HTML to the browser.
- Benefits include improved initial loading performance, better SEO, and better accessibility.
- Angular Universal is the official library for SSR in Angular.
What is Angular Universal?
- Angular Universal is the official library for implementing Server-Side Rendering (SSR) in Angular applications.
- It allows you to run your Angular application on a server environment and generate static HTML.
What are the benefits of using Server-Side Rendering?
- Faster initial page load time.
- Improved SEO (Search Engine Optimization) as search engine crawlers can easily index the content.
- Better user experience, especially on slow networks or devices.
- Improved accessibility.
What is State Management in Angular?
- State management is the process of managing the data that represents the current state of your application.
- As applications grow, managing shared data between components can become complex.
- State management libraries provide a structured way to handle application state.
Name some popular State Management libraries for Angular.
- NgRx
- Akita
- NGXS
Explain the core concepts of NgRx.
- Store: Holds the application state as a single, immutable object.
- Actions: Plain objects that describe events that happen in the application.
- Reducers: Pure functions that take the current state and an action and return a new state.
- Selectors: Pure functions that extract slices of state from the store.
- Effects: Handle side effects (e.g., asynchronous operations like HTTP requests) and dispatch new actions.
What is the purpose of Services in NgRx?
- In NgRx, services are typically used for handling side effects, such as making HTTP requests or interacting with local storage.
- These side effects are triggered by actions and managed within Effects.
What is the difference between a Component and a Service in the context of NgRx?
- Component: Dispatches actions to the store and selects data from the store to display in the view.
- Service (in NgRx context): Handles side effects triggered by actions, such as fetching data from an API.
What is the role of the Redux pattern in NgRx?
- NgRx is heavily inspired by the Redux pattern.
- It follows the principles of a single source of truth (the store), state being read-only, and changes being made through pure functions (reducers).
What are Unit Tests in Angular?
- Unit tests are tests that verify the functionality of individual units of code, such as components, services, pipes, or directives, in isolation.
- They are written using a testing framework (commonly Jasmine) and a test runner (commonly Karma).
What are End-to-End (E2E) Tests in Angular?
- E2E tests simulate user interactions with the entire application, testing the flow from the user interface to the backend and back.
- They verify that different parts of the application work together correctly.
- Protractor was the standard E2E testing framework for Angular, but newer options like Cypress and Playwright are becoming more popular.
What is the difference between Unit Tests and E2E Tests?
- Unit Tests: Test small, isolated pieces of code. Fast to run. Focus on individual logic.
- E2E Tests: Test the entire application flow from the user's perspective. Slower to run. Focus on system integration.
How do you write Unit Tests for an Angular Component?
- You use the
TestBed
to create a testing module that configures the testing environment. - You create an instance of the component and its host fixture.
- You can then interact with the component's properties and methods and assert the expected behavior.
What is TestBed
?
TestBed
is the primary utility for writing unit tests for Angular applications.- It creates an Angular testing module that you can configure with the components, services, and other dependencies needed for your test.
How do you mock dependencies in Unit Tests?
- You can mock dependencies (like services) by providing a test double (e.g., a spy, a stub, or a fake) in the
providers
array of theTestBed
configuration. - This allows you to control the behavior of the dependency during the test.
What is the purpose of the async
and fakeAsync
utilities in Angular testing?
async
: Runs asynchronous code within a test. It waits for all pending asynchronous operations to complete before finishing the test.fakeAsync
: Creates a fake asynchronous environment. It allows you to simulate the passage of time usingtick()
and execute asynchronous code synchronously within the test. This is often preferred for testing asynchronous code as it provides more control.
What is the difference between async
and fakeAsync
?
async
uses the browser's native asynchronous APIs and waits for them to complete.fakeAsync
creates a virtual time environment, allowing you to control the execution of asynchronous code usingtick()
.fakeAsync
is generally easier to work with and provides more deterministic tests for asynchronous code.
What is the purpose of the
element?
is a template element that Angular uses internally.- It's typically used with structural directives (like
*ngIf
,*ngFor
) or for defining reusable template fragments that can be rendered conditionally or repeatedly. - Content within
is not rendered directly unless explicitly instructed by a directive.
What is the difference between
and
?
is a grouping element that doesn't introduce an extra element into the DOM. It's useful for applying structural directives without adding unnecessary wrapper elements.
is a template element that holds content that is not rendered directly. It's used for defining reusable or conditionally rendered template fragments.
What is the purpose of ChangeDetectorRef
?
ChangeDetectorRef
is a service that allows you to manually trigger or detach change detection for a component.- You might use it in scenarios where you need more fine-grained control over change detection, especially when using
ChangeDetectionStrategy.OnPush
.
When would you use ChangeDetectorRef
?
- When using
ChangeDetectionStrategy.OnPush
and you need to trigger change detection manually because of an event or data change that Angular's default strategy wouldn't detect (e.g., a mutable object property change). - When detaching and reattaching the change detector for performance optimization in specific scenarios.
What are Zones in Angular (related to zone.js
)?
- Zones are execution contexts that persist across asynchronous tasks.
zone.js
patches browser APIs to create these zones.- Angular's change detection relies on zones to know when asynchronous operations (like button clicks, HTTP responses, timers) have completed, signaling that it might need to check for changes in the application state.
What is the significance of the @angular/core
package?
@angular/core
is the fundamental Angular package.- It contains the core runtime and compiler that all Angular applications need.
- It provides decorators like
@Component()
,@NgModule()
,@Injectable()
, and core services.
What is the significance of the @angular/common
package?
@angular/common
provides common directives, pipes, and services used in most Angular applications.- It includes directives like
NgIf
,NgFor
,NgSwitch
, pipes likeDatePipe
andCurrencyPipe
, and services likeHttpClient
.
What is the significance of the @angular/platform-browser
package?
@angular/platform-browser
provides platform-specific code for running Angular applications in a browser environment.- It includes the necessary code to interact with the browser DOM and bootstrap the application.
BrowserModule
, which you import in your root module, comes from this package.
What is the significance of the @angular/platform-browser-dynamic
package?
@angular/platform-browser-dynamic
provides the compiler that compiles your Angular templates in the browser at runtime (JIT compilation).- It's used during development. For production builds with AOT, this package is typically not included in the final bundle.
What is the significance of the @angular/router
package?
@angular/router
provides the routing capabilities for Angular applications.- It allows you to define routes, navigate between views, and handle URL parameters and query parameters.
What is the significance of the @angular/forms
package?
@angular/forms
provides the functionality for working with forms in Angular, including template-driven forms and reactive forms.- It includes directives like
ngModel
and classes likeFormGroup
andFormControl
.
What is the significance of the @angular/animations
package?
@angular/animations
provides the functionality for creating animations in Angular applications.- It allows you to define and control transitions between different states of your application's UI.
What is the purpose of the package.json
file in an Angular project?
package.json
is a manifest file that contains metadata about your Angular project.- It lists the project's dependencies (required libraries and packages) and development dependencies (tools needed for development, testing, and building).
- It also defines scripts for common tasks (e.g.,
start
,build
,test
).
What is the purpose of the angular.json
file?
angular.json
is the configuration file for the Angular CLI workspace.- It defines project settings, build configurations, test configurations, and other CLI-related settings for your Angular projects within the workspace.
What is the purpose of the tsconfig.json
file?
tsconfig.json
is the configuration file for the TypeScript compiler.- It specifies compiler options, such as the target JavaScript version, module system, and where to find TypeScript files.
What is the purpose of the tslint.json
file (or equivalent in newer versions)?
tslint.json
(or configuration for ESLint in newer versions) defines linting rules for your TypeScript code.- Linters help maintain code quality, consistency, and catch potential errors.
What is the purpose of the .gitignore
file?
.gitignore
is a file used by Git to specify intentionally untracked files that Git should ignore.- In an Angular project, it typically includes directories like
node_modules
(dependencies),dist
(build output), and editor configuration files.
What is the purpose of the polyfills.ts
file?
polyfills.ts
contains polyfills that are needed to provide support for modern JavaScript features in older browsers.- Angular relies on certain browser APIs that might not be available in all browsers, and polyfills fill those gaps.
What is the purpose of the main.ts
file?
main.ts
is the entry point of your Angular application.- It bootstraps the root module (
AppModule
), which starts the application.
What is the purpose of the index.html
file?
index.html
is the main HTML file that serves as the entry point for your Angular application in the browser.- The Angular application is typically rendered within the root component's selector in this file (e.g.,
).
What is the purpose of the styles.css
(or styles.scss
) file?
- This file contains global styles that apply to the entire application.
- Component-specific styles are typically defined in the component's
.css
or.scss
file.
What is the difference between component styles and global styles?
- Component Styles: Styles defined within a component's
styleUrls
orstyles
property. By default (with ViewEncapsulation.Emulated), they are scoped to the component's view. - Global Styles: Styles defined in the main
styles.css
file. They apply to all elements in the application.
How do you handle assets in an Angular project?
- Assets (like images, fonts, and other static files) are typically placed in the
src/assets
folder. - During the build process, the Angular CLI copies the contents of the
assets
folder to the build output directory (e.g.,dist/
)./assets - You can then reference these assets in your templates using relative paths from the root of the application.
How do you configure proxying API requests in Angular development?
- You can configure a proxy in the
proxy.conf.json
file (or similar) to redirect API requests from your development server to a backend server. - This helps avoid CORS issues during development.
- You then reference this proxy configuration in your
angular.json
file.
What is Strict Mode in Angular?
- Strict mode is a configuration option in newer Angular projects that enables stricter type checking and other best practices.
- It helps catch potential errors earlier in the development process and improves code maintainability.
- It's enabled by default when creating new projects with recent Angular CLI versions.
What are Schematics in Angular?
- Schematics are code generators that automate repetitive tasks in Angular development, such as creating new components, services, or modules.
- The Angular CLI uses schematics internally (e.g.,
ng generate component
). - You can also create custom schematics.
What is RxJS?
- RxJS (Reactive Extensions for JavaScript) is a library for reactive programming using Observables.
- It provides a collection of operators for working with streams of data and handling asynchronous operations.
- Angular uses RxJS extensively for handling events, HTTP requests, and other asynchronous tasks.
What are RxJS Operators?
- Operators are functions that operate on Observables to transform, filter, combine, or perform other actions on the data stream.
- They are used to chain operations on Observables.
- Examples:
map
,filter
,mergeMap
,switchMap
,debounceTime
,takeUntil
.
Explain the difference between mergeMap
and switchMap
.
mergeMap
(orflatMap
): Subscribes to each inner Observable that is created. It can have multiple inner Observables running concurrently. The output stream merges the values from all active inner Observables.switchMap
: Only subscribes to the *latest* inner Observable that is created. It cancels any previous inner Observables. This is useful for scenarios like typeahead search where you only care about the results of the most recent request.
When would you use switchMap
?
- Use
switchMap
when you only care about the response from the most recent Observable, and you want to cancel previous pending Observables. - Common use cases include typeahead search (cancel previous search requests when the user types again) or handling button clicks where you only want to process the latest click.
What is the purpose of the takeUntil
operator?
takeUntil
is an RxJS operator that unsubscribes from the source Observable when another "notifier" Observable emits a value.- It's commonly used to prevent memory leaks by automatically unsubscribing from Observables when a component is destroyed.
Example:
import { Component, OnInit, OnDestroy } from '@angular/core';
import { DataService } from './data.service';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.html'
})
export class MyComponent implements OnInit, OnDestroy {
private destroy$ = new Subject();
data: any;
constructor(private dataService: DataService) { }
ngOnInit() {
this.dataService.getData().pipe(
takeUntil(this.destroy$)
).subscribe(data => {
this.data = data;
});
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
}
What is the difference between Subject
and BehaviorSubject
?
Subject
: An Observable that can multicast (broadcast) values to multiple observers. It doesn't have an initial value and doesn't retain the last emitted value for new subscribers.BehaviorSubject
: A type of Subject that has an initial value and emits the *last* emitted value to new subscribers immediately upon subscription. It's useful for representing a value that changes over time and you want new subscribers to receive the current value.
What is the purpose of the async
keyword in TypeScript?
- The
async
keyword is used to declare an asynchronous function. - An
async
function implicitly returns a Promise. - Within an
async
function, you can use theawait
keyword to pause execution until a Promise resolves.
What is the purpose of the await
keyword in TypeScript?
- The
await
keyword can only be used inside anasync
function. - It pauses the execution of the
async
function until the Promise it's applied to resolves. - It returns the resolved value of the Promise.
How do you handle errors in Observables?
- You can handle errors in Observables using the
error
callback in thesubscribe()
method. - You can also use RxJS error handling operators like
catchError
,retry
, andretryWhen
within the Observable pipeline.
Example with catchError
:
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
this.http.get('/api/data').pipe(
catchError(error => {
console.error('An error occurred:', error);
return throwError('Something went wrong'); // Re-throw the error or return a new Observable
})
).subscribe(data => {
console.log(data);
});
What is the purpose of the defer
operator in RxJS?
defer
creates an Observable that, when subscribed to, calls an Observable factory function to create an Observable and then subscribes to that Observable.- This is useful for creating Observables lazily, where the creation of the Observable is deferred until subscription.
What is the purpose of the forkJoin
operator in RxJS?
forkJoin
takes an array or object of Observables and returns a new Observable that emits a single value when all source Observables complete.- The emitted value is an array of the last values emitted by each source Observable (in the same order as the input array) or an object with the keys corresponding to the input object.
- It's useful for performing multiple asynchronous operations in parallel and waiting for all of them to complete.
What is the purpose of the combineLatest
operator in RxJS?
combineLatest
takes an array of Observables and returns a new Observable that emits a value whenever *any* of the source Observables emits a value, after all source Observables have emitted at least one value.- The emitted value is an array containing the latest values from all source Observables.
- It's useful for combining values from multiple sources that are constantly changing.
What is the purpose of the merge
operator in RxJS?
merge
takes multiple Observables and returns a new Observable that emits values from all source Observables as they arrive.- It interleaves the values from the source Observables.
What is the purpose of the concat
operator in RxJS?
concat
takes multiple Observables and returns a new Observable that emits values from the source Observables one after another, in the order they are provided.- It waits for each source Observable to complete before subscribing to the next one.
What is the purpose of the debounceTime
operator in RxJS?
debounceTime
is an RxJS operator that waits for a specified period of inactivity before emitting the last value from the source Observable.- It's commonly used to limit the rate of emissions from an Observable, such as when handling user input in a search box to avoid making too many requests.
What is the purpose of the distinctUntilChanged
operator in RxJS?
distinctUntilChanged
is an RxJS operator that only emits a value from the source Observable if it is different from the previously emitted value.- It's useful for filtering out consecutive duplicate values.
What is the purpose of the tap
(or do
) operator in RxJS?
tap
is an RxJS operator that performs a side effect for each emission from the source Observable without modifying the emitted value.- It's commonly used for debugging, logging, or performing other side effects within the Observable pipeline.
What is the purpose of the map
operator in RxJS?
map
is an RxJS operator that transforms each emitted value from the source Observable into a new value.- It applies a provided function to each value and emits the result.
What is the purpose of the filter
operator in RxJS?
filter
is an RxJS operator that emits only those values from the source Observable that satisfy a provided condition.- It filters out values that don't meet the criteria.
How do you handle subscriptions in Angular to prevent memory leaks?
- You should always unsubscribe from Observables when the component or service that subscribed to them is destroyed.
-
Common methods include:
- Using the
async
pipe in templates (automatically unsubscribes). - Using the
takeUntil
operator with a Subject that emits when the component is destroyed (e.g., inngOnDestroy
). - Manually calling the
unsubscribe()
method on the Subscription object inngOnDestroy
.
- Using the
What is the purpose of the index.ts
file in a directory?
- An
index.ts
file in a directory serves as an "export barrel". - It re-exports modules, components, services, etc., from that directory, making it easier to import them from a single file instead of multiple individual files.
What is the purpose of the environment.ts
files?
environment.ts
andenvironment.prod.ts
files are used to store environment-specific configuration values.- You can define different values for development and production environments (e.g., API endpoints, feature flags).
- The Angular CLI automatically replaces the
environment.ts
file withenvironment.prod.ts
during a production build.
How do you use environment variables in your Angular application?
- You import the
environment
object from the appropriate environment file (e.g.,import { environment } from '../environments/environment';
). - You can then access the properties of the
environment
object in your components and services.
What is the purpose of the HttpClientXsrfModule
?
HttpClientXsrfModule
provides protection against Cross-Site Request Forgery (CSRF) attacks when using theHttpClient
.- It automatically adds a CSRF token to outgoing requests and validates incoming responses.
What is the purpose of the ServiceWorkerModule
?
ServiceWorkerModule
is used to register a service worker in your Angular application.- Service workers enable features like offline support and push notifications.
- They act as a proxy between the browser and the network.
What is a PWA (Progressive Web App)?
- A Progressive Web App (PWA) is a web application that uses modern web technologies to provide a user experience similar to a native mobile application.
- Key features include offline support, push notifications, and the ability to be installed on the user's home screen.
- Angular has built-in support for creating PWAs using the Angular CLI and the
@angular/service-worker
package.
How do you make an Angular application a PWA?
- You can use the Angular CLI command
ng add @angular/pwa
. - This command adds the necessary dependencies (
@angular/service-worker
), configures a service worker, and creates a manifest file.
What is the purpose of the manifest.webmanifest
file?
- The
manifest.webmanifest
file is a JSON file that provides information about your web application to the browser. - It's used by PWAs to define properties like the application name, icons, start URL, and display mode.
- This information is used when a user adds the PWA to their home screen.
What is the purpose of the ng build --prod
command?
ng build --prod
builds your Angular application for production.-
It enables various optimizations, including:
- AOT compilation
- Bundling and minification of code
- Dead code elimination (tree shaking)
- Hashing of asset filenames for cache busting
- Production environment configuration
- The output is placed in the
dist
directory.
What is Tree Shaking?
- Tree shaking (or dead code elimination) is an optimization process that removes unused code from your application's final bundle.
- Angular applications, especially when built with AOT and modern module bundlers like Webpack, benefit from tree shaking, resulting in smaller bundle sizes.
What is Bundling and Minification?
- Bundling: Combining multiple JavaScript, CSS, and HTML files into fewer files to reduce the number of HTTP requests needed to load the application.
- Minification: Removing unnecessary characters (like whitespace, comments, and short variable names) from code to reduce file size.
- These are standard optimization techniques applied during the production build process.
What is the purpose of the zone.js
library in Angular?
zone.js
patches asynchronous browser APIs (likesetTimeout
,setInterval
, event listeners, XHR).- It creates "zones" which provide a context for asynchronous operations.
- Angular uses
zone.js
to detect when asynchronous operations complete, triggering change detection.
What are Zones in Angular (revisited)?
- Zones are execution contexts that persist across asynchronous tasks.
zone.js
patches browser APIs to create these zones.- Angular's change detection relies on zones to know when asynchronous operations (like button clicks, HTTP responses, timers) have completed, signaling that it might need to check for changes in the application state.
What is the purpose of the BrowserModule
?
BrowserModule
is a module that is required for running Angular applications in a browser.- It provides essential services and directives needed for browser-based applications.
- You typically import
BrowserModule
only in the root module (AppModule
).
What is the purpose of the CommonModule
?
CommonModule
provides common directives (likeNgIf
,NgFor
,NgSwitch
) and pipes (likeDatePipe
,CurrencyPipe
) that are used in component templates.- Feature modules should import
CommonModule
instead ofBrowserModule
to avoid importing browser-specific services multiple times.
What is the difference between BrowserModule
and CommonModule
?
BrowserModule
is for the root module and provides browser-specific services and directives.CommonModule
is for feature modules and provides common directives and pipes without including browser-specific services.
What is Internationalization (i18n) and Localization (l10n) in Angular?
- Internationalization (i18n): The process of designing and developing an application in a way that it can be easily adapted to different languages and regions without requiring engineering changes to the core code.
- Localization (l10n): The process of adapting an internationalized application to a specific language and region. This involves translating text, formatting dates and numbers, and handling cultural conventions.
How does Angular support i18n and l10n?
- Angular provides built-in support for i18n by allowing you to mark text in your templates for translation using the
i18n
attribute. - It also provides pipes for formatting dates, numbers, and currency according to different locales.
- The Angular CLI has commands to extract translation files and build localized versions of your application.
What is the purpose of the i18n
attribute?
- The
i18n
attribute is used to mark elements or attributes in your template for translation. - You can optionally provide a meaning and description to help translators.
Example:
Welcome
This is a paragraph.
What is the purpose of the @HostBinding()
decorator?
@HostBinding()
is an attribute decorator used to bind a property of a directive or component class to a property of its host element.- It's commonly used to dynamically add or remove CSS classes or styles on the host element.
Example:
import { Directive, HostBinding, Input } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
@Input('appHighlight') highlightColor: string;
@HostBinding('style.backgroundColor') backgroundColor: string;
// ... logic to set backgroundColor based on highlightColor
}
What is the purpose of the @HostListener()
decorator?
@HostListener()
is an attribute decorator used to listen for events on the host element of a directive or component and react to them.- It takes the event name as an argument.
Example:
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appClickLogger]'
})
export class ClickLoggerDirective {
@HostListener('click') onClick() {
console.log('Host element clicked!');
}
}
What is the difference between @HostBinding()
and @HostListener()
?
@HostBinding()
binds a class property to a host element property (setting values).@HostListener()
listens for events on the host element and executes a method when the event occurs.
What is the purpose of the ElementRef
?
ElementRef
is a wrapper around a native DOM element.- It provides access to the underlying element.
- While it provides access to the native element, it's generally recommended to use
Renderer2
for DOM manipulation for platform independence.
What is the purpose of the TemplateRef
?
TemplateRef
represents an Angular template (typically defined using
).- It allows you to create embedded views from the template.
What is the purpose of the ViewContainerRef
?
ViewContainerRef
represents a container where one or more views can be attached.- It's used to dynamically create and manage views (e.g., embedding a template using
TemplateRef.createEmbeddedView()
or creating a component dynamically usingComponentFactoryResolver
).
What is the purpose of the ComponentFactoryResolver
?
ComponentFactoryResolver
is a service that allows you to dynamically create components at runtime.- It's used in conjunction with
ViewContainerRef
to instantiate components and insert them into the DOM.
When would you dynamically create components?
-
You might dynamically create components in scenarios like:
- Building dynamic forms or layouts where the components to be rendered are not known at compile time.
- Creating modal dialogs or popups.
- Implementing features like drag-and-drop where components are moved and re-rendered.
What is the purpose of the RouterModule
?
- The
RouterModule
is the main module for Angular routing. - It provides the necessary directives, services, and configuration options for implementing navigation in your application.
What is the purpose of the RouterOutlet
directive?
is a directive that marks the location in the template where the routed components should be displayed.- When the router navigates to a route, it renders the corresponding component within the
RouterOutlet
.
What is the purpose of the RouterLink
directive?
[routerLink]
is a directive used to create navigation links in your templates.- It takes a router link array as input, which specifies the path and optional parameters for the route to navigate to.
Example:
View Product
What is the purpose of the ActivatedRoute
service?
ActivatedRoute
is a service that provides information about the currently active route.- You can use it to access route parameters, query parameters, route data, and URL segments.
What is the purpose of the Router
service?
- The
Router
service provides programmatic navigation capabilities. - You can use its methods (like
navigate()
andnavigateByUrl()
) to trigger navigation from your component code.
What is the difference between routerLink
and Router.navigate()
?
routerLink
is a directive used in templates for declarative navigation.Router.navigate()
is a method used in component code for programmatic navigation.
What is the purpose of the Location
service?
- The
Location
service is an Angular service that interacts with the browser's history stack. - It allows you to navigate back and forward in the browser's history.
Example:
import { Location } from '@angular/common';
constructor(private location: Location) { }
goBack() {
this.location.back();
}
What is the purpose of the RendererFactory2
?
RendererFactory2
is a factory that createsRenderer2
instances.- It's used internally by Angular to provide the appropriate renderer for the current rendering environment.
What is the purpose of the PlatformRef
?
PlatformRef
represents the Angular platform, which is the top-level entry point for bootstrapping Angular applications.- It provides methods for bootstrapping modules and destroying the platform.
What is the purpose of the ApplicationRef
?
ApplicationRef
represents the running Angular application.- It provides methods for bootstrapping components, triggering change detection, and detaching views.
What is the difference between PlatformRef
and ApplicationRef
?
PlatformRef
is the entry point for bootstrapping the entire Angular platform.ApplicationRef
represents a single running Angular application within the platform.
What is the purpose of the NgZone
service?
NgZone
is an Angular service that wraps thezone.js
library.- It provides methods to run code inside or outside the Angular zone.
- Running code outside the Angular zone can improve performance by preventing unnecessary change detection cycles for operations that don't affect the application state.
When would you run code outside the Angular zone using NgZone.runOutsideAngular()
?
-
You would run code outside the Angular zone for performance-intensive tasks or operations that don't need to trigger change detection, such as:
- Third-party library callbacks that don't interact with Angular data.
- Complex calculations or animations that don't update component properties.
- Handling events that don't require immediate UI updates.
What is the purpose of the ChangeDetectorRef.markForCheck()
method?
- When using
ChangeDetectionStrategy.OnPush
, if a component's input property is a mutable object and a property of that object changes (without changing the object reference itself), Angular's default change detection won't detect the change. markForCheck()
marks the component and its ancestors as dirty, ensuring that the component will be checked during the next change detection cycle.
What is the purpose of the ChangeDetectorRef.detectChanges()
method?
detectChanges()
triggers a change detection cycle for the current component and its descendants.- It's a way to manually force change detection.
- Use with caution as frequent manual change detection can impact performance.
What is the purpose of the ChangeDetectorRef.detach()
and ChangeDetectorRef.reattach()
methods?
detach()
detaches the change detector from the view hierarchy. Changes in the component or its descendants will no longer trigger change detection.reattach()
reattaches the change detector to the view hierarchy.- These methods are used for advanced performance optimization in specific scenarios.
What is the purpose of the @SkipSelf()
decorator?
@SkipSelf()
is a dependency injection decorator that tells Angular to start looking for a dependency (e.g., a service) in the injector hierarchy *above* the current component or directive's injector.- It's useful when you want to ensure you get a service instance from a parent injector, rather than potentially getting a new instance from the current injector.
What is the purpose of the @Self()
decorator?
@Self()
is a dependency injection decorator that tells Angular to only look for a dependency (e.g., a service) in the injector of the *current* component or directive.- If the dependency is not provided at this level, an error will occur.
What is the purpose of the @Optional()
decorator?
@Optional()
is a dependency injection decorator that makes a dependency optional.- If Angular cannot find the dependency in the injector hierarchy, it will inject
null
instead of throwing an error.
What is the purpose of the @Host()
decorator?
@Host()
is a dependency injection decorator that tells Angular to look for a dependency (e.g., a service) in the injector of the *host* component.- It stops searching the hierarchy at the host component's injector.
Explain the injector hierarchy in Angular.
- Angular has a hierarchical dependency injection system.
- Each component and directive has its own injector.
- When a component or directive requests a dependency, Angular looks for it in its own injector first, then in its parent's injector, and so on, up to the root injector (provided by
AppModule
). - The root injector is a singleton and contains services available throughout the application.
What is the purpose of the entryComponents
array in @NgModule
(deprecated)?
entryComponents
was used to tell Angular to compile and create aComponentFactory
for components that were not referenced in any template but were going to be created dynamically (e.g., in routing or withViewContainerRef
).- This array is deprecated in modern Angular versions because the compiler can now automatically determine entry components.
What is the purpose of the JIT
compiler?
- The JIT (Just-in-Time) compiler compiles your Angular templates and code in the browser at runtime.
- It's used during development for faster build times.
What is the purpose of the AOT
compiler?
- The AOT (Ahead-of-Time) compiler compiles your Angular templates and code into native JavaScript during the build process (before the browser).
- It's used for production builds and provides performance benefits.
What is the purpose of the @angular/compiler
package?
@angular/compiler
contains the Angular compiler, which is responsible for compiling Angular templates into JavaScript code.- Both JIT and AOT compilation use this package.
What is the purpose of the @angular/core/testing
package?
@angular/core/testing
provides utilities for writing unit tests for Angular code.- It includes
TestBed
,async
, andfakeAsync
.
What is the purpose of the @angular/platform-browser/testing
package?
@angular/platform-browser/testing
provides utilities for testing Angular applications that run in a browser environment.- It includes
BrowserDynamicTestingModule
andplatformBrowserDynamicTesting
.
What is the purpose of the @angular/router/testing
package?
@angular/router/testing
provides utilities for testing Angular routing.- It includes
RouterTestingModule
.
What is the purpose of the @angular/common/http/testing
package?
@angular/common/http/testing
provides utilities for testing HTTP requests made withHttpClient
.- It includes
HttpClientTestingModule
andHttpTestingController
.
How do you test HTTP requests in Angular?
- You use the
HttpClientTestingModule
andHttpTestingController
from@angular/common/http/testing
. - You make the HTTP request in your test and then use
HttpTestingController
to expect, flush, and verify the request.
What is the purpose of the HttpTestingController
?
HttpTestingController
is a utility provided byHttpClientTestingModule
that allows you to mock and control HTTP requests made withHttpClient
in your tests.- You can use it to expect specific requests, provide mock responses (flush), and verify that no unexpected requests were made.
What is the purpose of the FormArray
in Reactive Forms?
FormArray
is a type ofFormGroup
that represents a collection ofFormControl
orFormGroup
instances.- It's used to manage dynamic lists of form controls, such as a list of email addresses or items in a shopping cart.
How do you add and remove controls in a FormArray
?
- You can use the
push()
method to add a newFormControl
orFormGroup
to theFormArray
. - You can use the
removeAt()
method to remove a control at a specific index.
What is the purpose of the ControlValueAccessor
interface?
ControlValueAccessor
is an interface that allows you to create custom form controls that can be used with Angular's form directives (ngModel
,formControlName
).- It provides methods to bridge the gap between the Angular form model and the native DOM element or a custom component.
When would you implement ControlValueAccessor
?
- You would implement
ControlValueAccessor
when you need to create a custom component that acts as a form input and you want it to work seamlessly with Angular's form validation and data binding. - Examples include custom date pickers, rating components, or rich text editors.
What is the purpose of the @Attribute()
decorator?
@Attribute()
is a parameter decorator used in a component or directive's constructor to inject the value of a static attribute from the host element.- Unlike
@Input()
, it retrieves the initial string value of the attribute and does not react to changes.
What is the purpose of the @Inject()
decorator?
@Inject()
is a parameter decorator used to explicitly specify a token that Angular should use to inject a dependency.- It's useful when the type of the dependency is not available at compile time or when injecting primitive values or objects that don't have a class token.
What is the purpose of the InjectionToken
?
InjectionToken
is a class used to create a unique token for dependency injection.- It's used when injecting primitive values, objects, or services that don't have a class as their injection token.
- Using an
InjectionToken
provides type safety and helps avoid naming conflicts.
What is the purpose of the useValue
provider?
useValue
is a provider configuration option used to provide a static value as a dependency.- It's useful for providing configuration objects, primitive values, or predefined instances.
Example:
import { InjectionToken } from '@angular/core';
export const APP_CONFIG = new InjectionToken('app.config');
// In your module providers:
providers: [
{ provide: APP_CONFIG, useValue: { apiUrl: '/api', version: '1.0' } }
]
What is the purpose of the useClass
provider?
useClass
is a provider configuration option used to provide an instance of a specific class as a dependency.- This is the most common way to provide services.
Example:
import { DataService } from './data.service';
import { MockDataService } from './mock-data.service';
// In your module providers:
providers: [
{ provide: DataService, useClass: MockDataService } // Use MockDataService instead of DataService
]
What is the purpose of the useFactory
provider?
useFactory
is a provider configuration option used to provide a dependency by calling a factory function.- The factory function can create the dependency based on other injected dependencies.
- This is useful for creating dependencies that require complex initialization or depend on runtime values.
Example:
import { HttpClient } from '@angular/common/http';
export function dataServiceFactory(http: HttpClient) {
return new DataService(http);
}
// In your module providers:
providers: [
{ provide: DataService, useFactory: dataServiceFactory, deps: [HttpClient] }
]
What is the purpose of the useExisting
provider?
useExisting
is a provider configuration option used to provide an alias for an existing dependency.- It allows you to inject the same instance of a service using a different token.
Example:
import { LoggerService } from './logger.service';
import { ConsoleLoggerService } from './console-logger.service';
// In your module providers:
providers: [
ConsoleLoggerService, // Provide the actual service
{ provide: LoggerService, useExisting: ConsoleLoggerService } // Alias LoggerService to ConsoleLoggerService
]
What is the purpose of the multi: true
provider option?
multi: true
is a provider configuration option that allows you to provide multiple values for a single injection token.- When a dependency is injected with
multi: true
, you receive an array of all registered providers for that token. - It's useful for scenarios like providing multiple HTTP interceptors.
What is the purpose of the APP_INITIALIZER
token?
APP_INITIALIZER
is an InjectionToken that allows you to define initialization tasks that should be performed before the application starts.- You provide a factory function that returns a Promise or an Observable. Angular waits for the Promise/Observable to complete before bootstrapping the root component.
- It's useful for loading configuration data or performing other setup tasks that are required before the application can render.
What is the purpose of the ErrorHandler
?
ErrorHandler
is a service that provides a hook for centralized error handling in your Angular application.- You can create a custom error handler by extending the base
ErrorHandler
class and providing it in your module. - This allows you to log errors, display user-friendly messages, or send errors to a reporting service.
What is the purpose of the Sanitizer
service?
Sanitizer
is a service used to protect against Cross-Site Scripting (XSS) attacks by cleaning HTML, styles, and URLs.- Angular automatically sanitizes values when binding to certain properties (like
[innerHtml]
), but you can use theSanitizer
service directly for more control or in custom directives.
What is the purpose of the DomSanitizer
service?
DomSanitizer
is a service that extendsSanitizer
and provides methods for marking values as safe to bypass sanitization.- You should only bypass sanitization when you are absolutely sure that the value is safe and comes from a trusted source.
- Methods include
bypassSecurityTrustHtml()
,bypassSecurityTrustStyle()
,bypassSecurityTrustScript()
,bypassSecurityTrustUrl()
, andbypassSecurityTrustResourceUrl()
.
When would you use DomSanitizer
?
- You would use
DomSanitizer
when you need to bind potentially unsafe values (like HTML from a backend API or user-provided input) to properties that would normally be sanitized by Angular, and you have validated that the content is safe. - For example, displaying rich text from a trusted source using
[innerHtml]
.
What is the purpose of the RendererType2
?
RendererType2
is an interface that describes the type of a renderer.- It includes properties like
id
,encapsulation
, andstyles
.
What is the purpose of the RendererFactory2
?
RendererFactory2
is a factory that createsRenderer2
instances.- It's used internally by Angular to provide the appropriate renderer for the current rendering environment.
What is the purpose of the Renderer2
(revisited)?
Renderer2
is an abstract class that provides a low-level API for interacting with the DOM.- It abstracts away the underlying rendering layer (e.g., browser DOM, server-side rendering).
- It's recommended to use
Renderer2
instead of directly manipulating the DOM when working with Angular to ensure your application can run in different environments (like server-side rendering).
What is the purpose of the ElementRef
(revisited)?
ElementRef
is a wrapper around a native DOM element.- It provides access to the underlying element.
- While it provides access to the native element, it's generally recommended to use
Renderer2
for DOM manipulation for platform independence.
What is the purpose of the TemplateRef
(revisited)?
TemplateRef
represents an Angular template (typically defined using
).- It allows you to create embedded views from the template.
What is the purpose of the ViewContainerRef
(revisited)?
ViewContainerRef
represents a container where one or more views can be attached.- It's used to dynamically create and manage views (e.g., embedding a template using
TemplateRef.createEmbeddedView()
or creating a component dynamically usingComponentFactoryResolver
).