Top Interview Questions
Angular is a powerful, open-source front-end framework developed and maintained by Google. It is widely used for building dynamic, scalable, and high-performance web applications, especially single-page applications (SPAs). Angular provides a complete solution for application development by offering a rich set of tools, libraries, and best practices out of the box. Over the years, Angular has evolved into a mature ecosystem that supports enterprise-level applications as well as smaller projects.
Angular is a TypeScript-based framework designed to simplify the development and testing of web applications. Unlike traditional JavaScript libraries that focus mainly on the view layer, Angular is a full-fledged framework that follows a structured approach. It enforces architectural patterns such as Model–View–Controller (MVC) or, more precisely, Component-based architecture, which helps developers write clean, maintainable, and reusable code.
Angular should not be confused with AngularJS (version 1.x). Angular (versions 2 and above) is a complete rewrite of AngularJS, offering better performance, modularity, and modern development practices.
One of the major strengths of Angular is the wide range of features it provides natively.
Component-Based Architecture
Angular applications are built using components. Each component consists of an HTML template, a TypeScript class, and optional CSS styles. Components control a portion of the user interface and can be reused throughout the application. This modular approach improves maintainability and scalability.
TypeScript Support
Angular uses TypeScript, a superset of JavaScript that adds static typing. TypeScript helps developers catch errors at compile time, improves code readability, and provides better tooling support such as auto-completion and refactoring.
Two-Way Data Binding
Angular supports two-way data binding, which keeps the model and the view in sync automatically. When data in the model changes, the view updates instantly, and when the user updates the view, the model reflects those changes. This feature significantly reduces boilerplate code.
Directives
Directives are special instructions in Angular that allow developers to manipulate the DOM. Angular provides built-in directives such as *ngIf, *ngFor, and ngClass, and also allows developers to create custom directives for specific behaviors.
Dependency Injection (DI)
Angular has a powerful dependency injection system that makes it easy to manage services and dependencies. DI improves testability and helps in writing loosely coupled code by injecting required services rather than creating them manually.
Angular applications are organized into modules, which are logical containers for components, directives, pipes, and services. The root module, typically called AppModule, bootstraps the application. Feature modules help in organizing large applications by grouping related functionality together.
Modules also support lazy loading, a performance optimization technique where modules are loaded only when needed. This reduces the initial load time of the application, making it faster and more efficient.
Angular templates are written in HTML with additional syntax to bind data and respond to user events. Angular supports different types of data binding:
Interpolation: Displays data from the component in the template using {{ }}.
Property Binding: Binds data to HTML element properties.
Event Binding: Listens to user events such as clicks or key presses.
Two-Way Binding: Combines property and event binding, commonly used with forms.
This powerful templating system allows developers to build dynamic and interactive user interfaces with ease.
Services in Angular are used to share data or logic across multiple components. Common use cases include fetching data from APIs, handling authentication, and performing business logic. Services are typically injected into components using Angular’s dependency injection system, ensuring better separation of concerns.
By centralizing logic in services, Angular promotes cleaner and more maintainable code.
Angular provides a built-in router that enables navigation between different views or components without reloading the page. Routing is essential for creating single-page applications. The Angular Router supports advanced features such as route parameters, guards, resolvers, and lazy-loaded routes.
Route guards are especially useful for controlling access to certain parts of the application, such as protecting routes that require authentication.
Angular offers two types of forms: Template-driven forms and Reactive forms.
Template-driven forms are simpler and rely heavily on HTML templates. They are suitable for small and simple applications.
Reactive forms, on the other hand, are more powerful and scalable. They use a model-driven approach where form logic is defined in the component class. Reactive forms provide better validation, testing, and control over form behavior, making them ideal for complex applications.
Angular includes a robust HTTP client module that allows developers to communicate with backend servers using RESTful APIs. The HTTP client supports features such as interceptors, error handling, and observables.
Using Angular with backend technologies like Node.js, Java, or PHP is straightforward, making it a popular choice for full-stack development.
Angular is designed with performance in mind. Features such as Ahead-of-Time (AOT) compilation, lazy loading, and change detection optimization help improve application speed and efficiency. AOT compilation converts Angular HTML and TypeScript code into efficient JavaScript during the build process, reducing runtime overhead.
Angular provides excellent testing support out of the box. It integrates well with tools like Jasmine, Karma, and Protractor. Developers can write unit tests for components, services, and pipes, as well as end-to-end tests for complete application workflows. This focus on testing makes Angular suitable for large-scale enterprise applications where reliability is critical.
The Angular ecosystem includes powerful tools such as the Angular CLI, which simplifies project setup, development, and deployment. With a few commands, developers can generate components, services, modules, and more. The CLI also handles tasks like bundling, testing, and optimization.
Angular also has a strong community and extensive documentation, making it easier for developers to learn and troubleshoot issues.
Answer:
Angular is a TypeScript-based open-source front-end framework developed and maintained by Google. It is used to build single-page applications (SPAs) where the page does not reload completely when navigating.
Angular follows a component-based architecture, making applications modular, reusable, and easy to maintain.
Key Features:
Component-based structure
Two-way data binding
Dependency Injection
Routing
Forms (Template-driven & Reactive)
Strong TypeScript support
Answer:
A Single Page Application loads only one HTML page, and content is updated dynamically without refreshing the entire page.
Example:
Gmail, Facebook, Angular apps
Benefits:
Faster navigation
Better user experience
Less server load
Angular is mainly used to build SPAs.
Answer:
A component is the basic building block of an Angular application. Each component controls a part of the UI.
A component consists of:
HTML Template – View
TypeScript Class – Logic
CSS – Styling
Decorator (@Component) – Metadata
Example:
@Component({
selector: 'app-home',
templateUrl: './home.component.html'
})
export class HomeComponent {}
Answer:
A module is a container that groups related components, services, directives, and pipes.
Every Angular app has at least one module:
AppModule (root module)
Example:
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
bootstrap: [AppComponent]
})
export class AppModule {}
Answer:
Data binding is the communication between the component class and the template.
Interpolation – {{ data }}
Property Binding – [property]="value"
Event Binding – (event)="method()"
Two-way Binding – [(ngModel)]
Example:
<input [(ngModel)]="username">
<p>{{ username }}</p>
Answer:
Two-way data binding allows automatic synchronization between the component and the view.
When the user updates the UI, the model updates automatically, and vice versa.
Used mainly with forms using ngModel.
Answer:
Directives are instructions in the DOM that change the behavior or appearance of elements.
Component Directives
Structural Directives – change DOM structure
*ngIf
*ngFor
*ngSwitch
Attribute Directives – change appearance
ngClass
ngStyle
Answer:
Used to conditionally display elements.
<div *ngIf="isLoggedIn">Welcome User</div>
Used to loop through data.
<li *ngFor="let item of items">{{ item }}</li>
Answer:
A service is a class used to share data or logic across multiple components.
Services are mainly used for:
API calls
Business logic
Shared data
Example:
@Injectable({
providedIn: 'root'
})
export class UserService {}
Answer:
Dependency Injection is a design pattern where Angular provides required objects automatically instead of creating them manually.
Benefits:
Loose coupling
Easy testing
Better maintainability
Answer:
Routing allows navigation between different views/components without reloading the page.
Example:
const routes: Routes = [
{ path: 'home', component: HomeComponent }
];
Used with <router-outlet>.
Answer:
Angular CLI is a command-line tool used to:
Create projects
Generate components/services
Build and test applications
Common Commands:
ng new app-name
ng serve
ng generate component home
Answer:
TypeScript is a superset of JavaScript that adds:
Static typing
Interfaces
Classes
Angular uses TypeScript because it:
Reduces runtime errors
Improves code readability
Supports large-scale applications
Answer:
Pipes transform data in templates.
Example:
{{ today | date:'short' }}
{{ name | uppercase }}
Custom Pipe:
@Pipe({name: 'reverse'})
export class ReversePipe {}
Answer:
Lifecycle hooks are methods that Angular calls during a component’s life.
Common Hooks:
ngOnInit
ngOnChanges
ngOnDestroy
| Angular | AngularJS |
|---|---|
| TypeScript | JavaScript |
| Component-based | MVC |
| Better performance | Slower |
| Mobile friendly | Limited |
Answer:
Forms built using HTML and directives like ngModel.
Pros: Easy to use
Cons: Less control
Answer:
Forms created in TypeScript using FormControl and FormGroup.
Pros: More control, scalable
Cons: Slightly complex
Answer:
HttpClient is used to communicate with backend APIs.
this.http.get('api/users').subscribe();
Answer:
Observable is used to handle asynchronous data like API responses.
Provided by RxJS.
@Component decorator?Answer:
@Component is a decorator that tells Angular that a class is a component and provides metadata about it.
Metadata includes:
selector
template / templateUrl
styleUrls
Example:
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
@NgModule decorator?Answer:
@NgModule defines an Angular module and groups related components, directives, pipes, and services.
Main properties:
declarations
imports
providers
bootstrap
selector in Angular?Answer:
A selector is used to include a component in HTML.
Example:
<app-login></app-login>
Answer:
View encapsulation controls whether a component’s styles affect other components.
Emulated (default)
None
ShadowDom
ngOnInit()?Answer:
ngOnInit() is a lifecycle hook called once after the component is initialized.
Used to:
Call APIs
Initialize data
ngOnInit() {
this.loadUsers();
}
constructor and ngOnInit?| Constructor | ngOnInit |
|---|---|
| Used for DI | Used for logic |
| Runs first | Runs after constructor |
| Avoid API calls | Best place for APIs |
@Input()?Answer:
Used to receive data from a parent component.
@Input() username: string;
@Output()?Answer:
Used to send data from child to parent using EventEmitter.
@Output() notify = new EventEmitter<string>();
Answer:
Angular automatically checks if data changes and updates the UI.
Triggered by:
Events
HTTP responses
Timers
async pipe?Answer:
Used to handle observables directly in templates.
{{ user$ | async }}
Answer:
Lazy loading loads modules only when required, improving performance.
{ path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }
Answer:
Guards control access to routes.
CanActivate
CanDeactivate
CanLoad
Answer:
HTTP Interceptors modify requests or responses.
Used for:
Authentication tokens
Logging
Error handling
trackBy in *ngFor?Answer:
Improves performance by tracking items uniquely.
<li *ngFor="let item of items; trackBy: trackById"></li>
ng-content?Answer:
Used for content projection (like slots).
<ng-content></ng-content>
ViewChild?Answer:
Accesses child component or DOM element.
@ViewChild('input') inputRef!: ElementRef;
ElementRef?Answer:
Provides direct access to DOM elements (use carefully).
Answer:
RxJS is a library for reactive programming using observables.
Common operators:
map
filter
subscribe
switchMap
| Promise | Observable |
|---|---|
| Single value | Multiple values |
| Cannot cancel | Can cancel |
| Executes immediately | Lazy execution |
FormControl?Answer:
Represents a single input field in reactive forms.
new FormControl('', Validators.required)
FormGroup?Answer:
Groups multiple form controls.
new FormGroup({
name: new FormControl('')
})
FormBuilder?Answer:
Simplifies reactive form creation.
Answer:
Used to validate form input.
Examples:
required
minlength
pattern
ng-template?Answer:
Defines reusable template blocks.
*ngSwitch?Answer:
Used for conditional rendering with multiple cases.
environment.ts?Answer:
Used to store environment-specific configurations like API URLs.
Answer:
Compiles Angular code at build time, improving performance.
Answer:
Compiles Angular code in the browser at runtime.
zone.js?Answer:
Used by Angular to detect async operations and trigger change detection.
renderer2?Answer:
Used to safely manipulate DOM elements.
Answer:
Angular architecture is based on modules, components, services, and dependency injection.
Modules – Logical grouping (AppModule, Feature Modules)
Components – UI + logic
Templates – HTML with Angular syntax
Services – Business logic, API handling
Dependency Injection – Service sharing
Routing – Navigation without reload
RxJS – Reactive data flow
Angular follows unidirectional data flow with change detection.
Answer:
Change detection determines how Angular updates the view when data changes.
Default
Checks entire component tree
Simpler but slower
OnPush
Runs only when:
Input reference changes
Observable emits
Event occurs inside component
changeDetection: ChangeDetectionStrategy.OnPush
Used in performance-critical apps.
Answer:
OnPush improves performance by skipping unnecessary checks.
Important: Object reference must change.
this.user = { ...this.user, name: 'John' };
Mutating existing object will NOT trigger change detection.
Answer:
Angular resolves dependencies in this order:
Component injector
Module injector
Root injector
Providing a service in:
component → new instance
root → singleton
| providedIn | providers |
|---|---|
| Tree-shakable | Not tree-shakable |
| Singleton | Can create multiple instances |
| Recommended | Legacy approach |
Answer:
Lazy loading loads modules only when needed.
Faster initial load
Reduced bundle size
Better scalability
Used with large enterprise applications.
Answer:
Standalone components eliminate the need for NgModules.
@Component({
standalone: true,
imports: [CommonModule]
})
Improves:
Simplicity
Tree-shaking
Faster builds
Answer:
OnPush change detection
trackBy in *ngFor
Lazy loading
AOT compilation
Pure pipes
Async pipe
Detaching change detector
Answer:
RxJS handles async operations and state flow.
Angular heavily depends on:
HttpClient
Forms
Router
Event streams
switchMap, mergeMap, concatMap| Operator | Use Case |
|---|---|
| switchMap | Cancel previous requests |
| mergeMap | Parallel execution |
| concatMap | Sequential execution |
Answer:
Unsubscribing prevents memory leaks.
async pipe
takeUntil
first()
Subscription cleanup in ngOnDestroy
Answer:
Angular uses:
PathLocationStrategy (default)
HashLocationStrategy
Path strategy requires server config.
Answer:
Fetches data before route loads.
Used to prevent blank UI.
Answer:
Guards secure routes.
Examples:
AuthGuard
Role-based access
Unsaved form protection
Answer:
Interceptors modify HTTP requests/responses.
Common uses:
JWT token
Global error handling
Loader
Answer:
Manages shared application state.
Popular libraries:
NgRx
Akita
NGXS
NgRx uses:
Store
Actions
Reducers
Effects
| Subject | BehaviorSubject |
|---|---|
| No initial value | Requires initial value |
| Subscribers get future values | Subscribers get latest value |
Answer:
HttpClient:
Observable-based
Interceptors
Typed responses
Error handling
Preferred in Angular.
Answer:
Reactive forms
Dynamic form generation
Custom validators
FormArray
Lazy loaded forms
Answer:
Allows passing HTML from parent to child.
Uses:
<ng-content></ng-content>
| ViewChild | ContentChild |
|---|---|
| Inside template | Projected content |
| AOT | JIT |
|---|---|
| Faster runtime | Faster dev |
| Smaller bundles | Larger bundles |
| Production | Development |
Answer:
Removes unused code during build.
Enabled via:
ES modules
providedIn: 'root'
Answer:
Detects async operations and triggers change detection.
Answer:
Augury
Chrome DevTools
Source maps
RxJS logging
Answer:
Server-side rendering for SEO and performance.
Answer:
JWT tokens
Interceptors
Guards
Refresh tokens
Answer:
Multiple Angular apps integrated together.
Tools:
Module Federation
Single-SPA
Answer:
Loads remote modules dynamically at runtime.
Used in enterprise apps.
Answer:
Manual DOM manipulation
Memory leaks
Overusing subscriptions
Heavy logic in components
Not using OnPush
Answer:
Angular bootstraps by loading the root module (AppModule) or a standalone component, then:
Loads dependencies
Compiles templates
Initializes root component
Starts change detection
In standalone apps:
bootstrapApplication(AppComponent)
NgZone and when do you use it?Answer:
NgZone controls Angular’s change detection.
Run heavy tasks outside Angular to improve performance
Re-enter Angular zone when UI update is required
this.ngZone.runOutsideAngular(() => {
// heavy computation
});
Answer:
OnPush change detection
Lazy loading + PreloadingStrategy
trackBy functions
Pure pipes
Detach change detector
Virtual scrolling
Avoid unnecessary subscriptions
Answer:
Loads lazy modules after initial load in background.
RouterModule.forRoot(routes, {
preloadingStrategy: PreloadAllModules
})
| Pure Pipe | Impure Pipe |
|---|---|
| Executes on input change | Executes every CD |
| Better performance | Slower |
| Default | Must be explicitly set |
ChangeDetectorRef?Answer:
Manually controls change detection.
Methods:
detectChanges()
markForCheck()
detach()
Used in performance optimization.
Answer:
Unsubscribe properly
Use async pipe
Use takeUntil pattern
Clear timers and event listeners
takeUntil pattern?Answer:
Ensures automatic unsubscribe.
private destroy$ = new Subject<void>();
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
}
Answer:
BehaviorSubject in services
Signals (newer Angular)
Component store pattern
Answer:
Signals are a reactive primitive for state management.
Benefits:
No subscriptions
Better performance
Predictable updates
count = signal(0);
| Observables | Signals |
|---|---|
| Async streams | Sync reactive values |
| RxJS-based | Angular core |
| Need unsubscribe | No unsubscribe |
Answer:
Removes NgModule complexity
Better tree shaking
Easier testing
Faster onboarding
Answer:
Using ViewContainerRef.
viewContainerRef.createComponent(MyComponent);
Answer:
Component Dev Kit provides low-level tools.
Examples:
DragDrop
Virtual Scroll
Overlay
Accessibility
Answer:
Store roles in token/session
Guard routes
Hide UI using directives
Answer:
Avoid bypassSecurityTrust
Use HttpOnly cookies
Sanitize user input
Prevent XSS & CSRF
DomSanitizer?Answer:
Protects application from XSS attacks.
Answer:
environment.ts files
Build-time replacements
Secure sensitive values via backend
Answer:
Lazy loading
Remove unused dependencies
Use standalone components
Tree shaking
ESBuild
Answer:
Modern build tools for faster builds and HMR.
Angular supports faster builders in newer versions.
Answer:
Used in large organizations to:
Share components
Independent deployments
Micro-frontend architecture
Answer:
Input/Output design
Content projection
Avoid tight coupling
Config-driven UI
| Smart | Dumb |
|---|---|
| Business logic | UI only |
| API calls | Emits events |
| State aware | Stateless |
Answer:
Multipart form data
Progress events
Size/type validation
Answer:
Unit tests: Jasmine, Karma
E2E tests: Cypress, Playwright
TestBed
Mock services
Answer:
Configures testing module for components/services.
Answer:
Using HttpTestingController.
Answer:
Browser-only APIs
Third-party libraries
State transfer
Caching
Answer:
Transfers server data to client during SSR.
Answer:
Feature-based modules
Shared core module
State management
Lazy loading
Strict linting