▲ Beginner Angular Interview Questions
This lesson covers Angular fundamentals that every developer must know before any interview. Master components, modules, data binding, directives, services, dependency injection, and routing. These questions reflect what interviewers ask at junior and entry-level roles.
Questions & Answers
01 What is Angular and what problems does it solve? ►
Core Angular is a full-featured, opinionated frontend framework built and maintained by Google. Written in TypeScript, it provides everything needed for large-scale web applications: routing, forms, HTTP client, animations, and state management patterns โ all in one package.
Problems Angular solves:
- Structure at scale โ Angular enforces a consistent architecture (modules, components, services, guards) that scales well across large teams and long-lived projects.
- Type safety โ Built-in TypeScript support catches errors at compile time, not at runtime.
- Two-way data binding โ Keeps UI and business logic in sync automatically without manual DOM manipulation.
- Dependency Injection โ Provides a powerful DI system for managing services and testability.
- Batteries included โ Routing, HTTP, forms, animations, i18n, testing utilities โ all official and integrated.
Angular is commonly compared to React and Vue. Unlike React (a library), Angular is a complete framework. It is popular for enterprise applications where consistency and tooling are critical.
02 Why does Angular use TypeScript? What are the benefits? ►
TypeScript Angular was rewritten in TypeScript from AngularJS (v1) and makes TypeScript a first-class requirement. TypeScript is a superset of JavaScript that adds static type checking.
Benefits for Angular development:
- Early error detection โ Catch type errors, missing properties, and API mismatches at compile time before they reach users.
- IDE intelligence โ Autocompletion, inline documentation, and refactoring tools work accurately with typed code.
- Decorators โ Angular’s
@Component,@Injectable,@NgModuledecorators are a TypeScript feature. - Interfaces and generics โ Model API responses and component inputs with precision.
- Refactoring safety โ Renaming a service method updates all callers automatically in a typed codebase.
// TypeScript catches this at compile time โ JS wouldn't
interface User { id: number; name: string; }
const user: User = { id: 1, name: 'Alice' };
console.log(user.email); // โ Error: Property 'email' does not exist
03 What is a Component in Angular? What does the @Component decorator do? ►
Core A Component is the fundamental UI building block in Angular. Every piece of the UI โ a button, a navbar, a page โ is a component. Each component controls a patch of the screen and consists of three parts:
- Template โ the HTML defining the view
- Class โ the TypeScript code containing properties and methods
- Styles โ scoped CSS for this component
import { Component } from '@angular/core';
@Component({
selector: 'app-greeting', // HTML tag name
template: `<h1>Hello, {{ name }}!</h1>`, // inline template
styles: [`h1 { color: #dd0031; }`]
})
export class GreetingComponent {
name = 'Angular';
}
The @Component decorator tells Angular that this class is a component and provides metadata: the CSS selector used to insert it (app-greeting), the template HTML, and the styles. Use templateUrl and styleUrls to reference external files instead of inline strings.
04 What is an NgModule? What does @NgModule declare? ►
Core An NgModule is a class decorated with @NgModule that groups related components, directives, pipes, and services into a cohesive functional block. Every Angular app has at least one root module (AppModule).
@NgModule({
declarations: [AppComponent, NavbarComponent, UserCardComponent], // components/directives/pipes that belong here
imports: [BrowserModule, RouterModule, HttpClientModule], // other modules this module needs
providers: [UserService, AuthGuard], // services registered here
exports: [NavbarComponent], // make these available to other modules
bootstrap: [AppComponent] // root component to launch (AppModule only)
})
export class AppModule {}
Key rules:
- A component must be declared in exactly ONE module
- To use a component from another module, that module must export it and you must import the module
- Angular 14+ introduced Standalone Components which can opt out of NgModules entirely
05 What are the four types of data binding in Angular? ►
Data Binding Angular supports four types of data binding between the component class and the template:
- Interpolation
{{ }}โ renders component property values as text in the template (one-way: class โ template)<p>Welcome, {{ username }}</p> - Property binding
[property]โ sets a DOM/component property from a class expression (one-way: class โ template)<img [src]="imageUrl"> - Event binding
(event)โ listens to DOM events and calls a class method (one-way: template โ class)<button (click)="save()">Save</button> - Two-way binding
[(ngModel)]โ syncs a form element value with a class property in both directions<input [(ngModel)]="username">
Two-way binding is shorthand for property binding + event binding combined: [(ngModel)] is syntactic sugar for [ngModel]="value" (ngModelChange)="value=$event". It requires FormsModule in your module.
06 What are Directives in Angular? What are the three types? ►
Directives Directives extend HTML with new behaviour. There are three types:
- Component directives โ Components are directives with a template. Every component is technically a directive.
- Structural directives โ Change the DOM structure by adding, removing, or repeating elements. Prefixed with
*.*ngIf="condition"โ add/remove element from DOM*ngFor="let item of items"โ repeat element for each item*ngSwitchโ switch between multiple templates
- Attribute directives โ Change the appearance or behaviour of an existing element without altering the DOM structure.
[ngClass]="{'active': isActive}"โ add/remove CSS classes[ngStyle]="{'color': textColor}"โ apply inline styles- Custom directives like
[appHighlight]
07 What is a Service in Angular and why is it needed? ►
Services A Service is a class that handles business logic, data fetching, or shared state โ anything that shouldn’t live inside a component. Components should be thin: they display data and respond to user events, nothing more.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({ providedIn: 'root' }) // auto-registered as a singleton
export class UserService {
constructor(private http: HttpClient) {}
getUsers(): Observable<User[]> {
return this.http.get<User[]>('/api/users');
}
}
Why services are essential:
- Code reuse โ one service can be injected into many components
- Separation of concerns โ keeps components focused on the UI
- Testability โ services are easy to mock in unit tests
- Shared state โ a singleton service can share data between sibling components without prop drilling
08 What is Dependency Injection (DI) in Angular? ►
DI Dependency Injection is a design pattern where a class receives its dependencies from an external source rather than creating them itself. Angular has a built-in hierarchical DI system.
// Without DI โ component creates its own dependency (hard to test, tightly coupled)
class UserComponent {
service = new UserService(); // โ
}
// With DI โ Angular injects the dependency (testable, loosely coupled)
@Component({ ... })
class UserComponent {
constructor(private userService: UserService) {} // โ
Angular injects this
}
How Angular DI works:
- Services are registered as providers โ in
@Injectable({ providedIn: 'root' })(singleton), in a module’sprovidersarray, or in a component’sprovidersarray (new instance per component) - Angular’s injector maintains a registry of providers and creates/caches instances
- When a component needs a service, Angular looks up the injector hierarchy and provides the correct instance
09 What is the Angular CLI? What are the most important commands? ►
Tooling The Angular CLI (Command Line Interface) is the official tool for creating, building, testing, and maintaining Angular applications. It automates boilerplate generation and follows Angular best practices.
# Create a new project ng new my-app --routing --style=scss # Generate items ng generate component features/user-list # or: ng g c ng generate service core/auth # or: ng g s ng generate module features/orders # or: ng g m ng generate pipe shared/currency-format # or: ng g p ng generate guard core/auth # or: ng g guard # Development server with hot reload ng serve --open # Production build (AOT, minification, tree-shaking) ng build --configuration=production # Run unit tests (Karma + Jasmine by default) ng test # Run end-to-end tests ng e2e
The CLI uses schematics under the hood โ code generation templates that can be extended by libraries (e.g., Angular Material: ng add @angular/material).
10 What are Angular lifecycle hooks? List the most important ones. ►
Lifecycle Angular calls lifecycle hook methods on components and directives at specific moments during creation, update, and destruction.
- ngOnChanges โ fires when an
@Input()property changes. First hook called. Receives aSimpleChangesobject with previous and current values. - ngOnInit โ fires once after the first
ngOnChanges. Best place for initialisation logic and data fetching. More reliable than the constructor. - ngDoCheck โ fires on every change detection cycle. Used for custom change detection logic.
- ngAfterViewInit โ fires once after the component’s view (and child views) are fully initialised. Use for DOM manipulation via
@ViewChild. - ngOnDestroy โ fires just before the component is destroyed. Critical for cleanup: unsubscribe from Observables, clear timers, remove event listeners.
The most used in practice are ngOnInit (setup) and ngOnDestroy (cleanup). The constructor should only be used for DI โ all initialisation logic goes in ngOnInit.
11 What are @Input() and @Output() decorators? ►
Communication @Input() and @Output() are the standard mechanism for parent-child component communication.
// CHILD component
@Component({ selector: 'app-product-card', template: `
<div>{{ product.name }} โ ยฃ{{ product.price }}</div>
<button (click)="addToCart()">Add</button>
`})
export class ProductCardComponent {
@Input() product!: Product; // receives data FROM parent
@Output() cartAdded = new EventEmitter<Product>(); // sends events TO parent
addToCart() { this.cartAdded.emit(this.product); }
}
// PARENT template
<app-product-card
[product]="selectedProduct" // passes data DOWN via @Input
(cartAdded)="onCartAdded($event)"> // listens UP via @Output
</app-product-card>
EventEmitter is an RxJS Subject under the hood. The parent handles the emitted event via event binding. For deeper communication between non-parent/child components, use a shared service with a Subject or BehaviorSubject.
12 What is a Pipe in Angular? Name the common built-in pipes. ►
Pipes A Pipe transforms data in a template before displaying it. Pipes are used with the | character in templates and can be chained.
<p>{{ price | currency:'GBP' }}</p> <!-- ยฃ1,234.56 -->
<p>{{ today | date:'dd/MM/yyyy' }}</p> <!-- 16/04/2026 -->
<p>{{ title | uppercase }}</p> <!-- ANGULAR PIPES -->
<p>{{ title | lowercase }}</p> <!-- angular pipes -->
<p>{{ user | json }}</p> <!-- { "id": 1, ... } -->
<p>{{ ratio | percent:'1.0-2' }}</p> <!-- 87.50% -->
<p>{{ longText | slice:0:100 }}</p> <!-- first 100 chars -->
<p>{{ obs$ | async }}</p> <!-- subscribes to Observable -->
Pure vs Impure pipes: Pure pipes (default) only re-execute when the input reference changes โ very efficient. Impure pipes re-execute on every change detection cycle. The async pipe is impure and also handles unsubscription automatically.
13 What is Angular Router and how do you set up basic routing? ►
Routing Angular Router handles client-side navigation between views without full page reloads. It maps URL paths to components.
// app-routing.module.ts
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'products', component: ProductListComponent },
{ path: 'products/:id',component: ProductDetailComponent },
{ path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) },
{ path: '**', component: NotFoundComponent } // wildcard โ must be last
];
@NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] })
export class AppRoutingModule {}
<!-- app.component.html --> <nav> <a routerLink="/" routerLinkActive="active">Home</a> <a routerLink="/products" routerLinkActive="active">Products</a> </nav> <router-outlet></router-outlet> <!-- routed component renders here -->
Access route parameters with ActivatedRoute: this.route.snapshot.params['id'] or this.route.params.subscribe(p => ...) for reactive updates. Navigate programmatically with this.router.navigate(['/products', id]).
14 What is HttpClient in Angular? How do you make a GET request? ►
HTTP HttpClient is Angular’s built-in module for making HTTP requests. It returns RxJS Observables (not Promises), enabling powerful operators for transformation, error handling, and cancellation.
// 1. Import HttpClientModule in AppModule (or provideHttpClient() in Angular 15+)
// 2. Inject HttpClient in a service
@Injectable({ providedIn: 'root' })
export class ProductService {
private apiUrl = 'https://api.example.com/products';
constructor(private http: HttpClient) {}
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(this.apiUrl);
}
createProduct(product: Product): Observable<Product> {
return this.http.post<Product>(this.apiUrl, product);
}
}
// In a component
ngOnInit() {
this.productService.getProducts().subscribe({
next: products => this.products = products,
error: err => this.error = err.message,
complete: () => this.loading = false
});
}
15 What is the difference between template-driven and reactive forms? ►
Forms
Template-driven forms (uses FormsModule):
- Logic is in the template using
ngModel,ngForm,required, etc. - Angular creates the form model implicitly
- Simpler for basic forms; harder to test and less flexible for complex validation
<form #f="ngForm" (ngSubmit)="submit(f)"> <input name="email" ngModel required email> </form>
Reactive forms (uses ReactiveFormsModule):
- Form model is created in the component class using
FormControl,FormGroup,FormBuilder - More explicit, fully testable, and scales to complex forms
- The recommended approach for most Angular applications
form = this.fb.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(8)]]
});
16 What is *ngIf and how does it differ from [hidden]? ►
Directives
<!-- *ngIf โ REMOVES element from DOM when false --> <div *ngIf="isLoggedIn">Welcome back!</div> <div *ngIf="isLoggedIn; else loginBlock">Welcome!</div> <ng-template #loginBlock><p>Please log in.</p></ng-template> <!-- [hidden] โ HIDES element with CSS display:none but keeps it in DOM --> <div [hidden]="!isLoggedIn">Welcome back!</div>
Key difference:
*ngIf="false"โ element is removed from the DOM. Child components are destroyed and their lifecycle hooks run. No memory used.[hidden]="true"โ element stays in the DOM (just invisible). Child components remain alive and use memory. Use when you need fast toggle without destroying state.
Use *ngIf for content that won’t be shown often. Use [hidden] for frequently toggled elements where you want to preserve their state.
17 What is *ngFor and how do you use trackBy? ►
Directives *ngFor iterates over a collection and renders a template for each item.
<ul>
<li *ngFor="let user of users; let i = index; let last = last">
{{ i + 1 }}. {{ user.name }} {{ last ? '(last)' : '' }}
</li>
</ul>
Available exported values: index, first, last, even, odd, count.
trackBy โ performance optimisation: By default, Angular re-renders the entire list when the array reference changes. trackBy tells Angular how to identify items so it only re-renders changed items:
<li *ngFor="let user of users; trackBy: trackById">{{ user.name }}</li>
// Component
trackById(index: number, user: User): number { return user.id; }
Without trackBy, replacing the entire array causes Angular to destroy and recreate all DOM nodes. With trackBy, Angular reuses DOM nodes for unchanged items โ critical for large or frequently updated lists.
18 What is the difference between constructor and ngOnInit? ►
Lifecycle
- Constructor โ called by JavaScript when the class is instantiated. At this point, Angular has not yet set input properties (
@Input()values are undefined). Only use for Dependency Injection โ injecting services via the constructor signature. - ngOnInit โ called by Angular after it has set all input properties. Use for all initialisation logic: fetch data, subscribe to observables, set up derived values from inputs.
export class UserProfileComponent implements OnInit {
@Input() userId!: number;
user: User | null = null;
constructor(private userService: UserService) {
// userId is undefined here โ don't use @Input values
}
ngOnInit(): void {
// userId is now set โ safe to use
this.userService.getUser(this.userId).subscribe(u => this.user = u);
}
}
19 What is the async pipe and why is it preferred over manual subscriptions? ►
RxJS The async pipe subscribes to an Observable or Promise and returns its latest value. When the component is destroyed, it automatically unsubscribes โ preventing memory leaks.
<!-- Using async pipe โ clean, no manual subscribe/unsubscribe -->
<div *ngIf="users$ | async as users; else loading">
<li *ngFor="let user of users">{{ user.name }}</li>
</div>
<ng-template #loading><p>Loading...</p></ng-template>
Without async pipe โ error-prone:
// Must manually unsubscribe or risk memory leaks
ngOnInit() { this.sub = this.users$.subscribe(u => this.users = u); }
ngOnDestroy() { this.sub.unsubscribe(); }
The async pipe also triggers change detection when a new value arrives, which is particularly important when using OnPush change detection strategy.
20 What is ViewEncapsulation in Angular? ►
Styles ViewEncapsulation controls how Angular scopes CSS styles to a component so they don’t bleed into other components.
- Emulated (default) โ Angular adds unique attribute selectors (
_ngcontent-xxx) to CSS rules and component elements, emulating Shadow DOM without native browser support. Styles are scoped to the component. - ShadowDom โ uses the native browser Shadow DOM API. True CSS isolation. Can’t be styled from outside without CSS custom properties.
- None โ no encapsulation. Styles are global and can affect other components. Useful for global base styles or third-party component overrides.
@Component({
selector: 'app-card',
template: `<div class="card">...</div>`,
styles: [`.card { border: 1px solid red; }`],
encapsulation: ViewEncapsulation.Emulated // default
})
21 What is ng-content? How does content projection work? ►
Patterns <ng-content> is Angular’s equivalent of React’s children prop โ it allows a component to render content that is passed in by the parent. This is called content projection.
// Reusable card component
@Component({ selector: 'app-card', template: `
<div class="card">
<div class="card-header"><ng-content select="[card-title]"></ng-content></div>
<div class="card-body"><ng-content></ng-content></div>
</div>
`})
export class CardComponent {}
// Parent usage โ passes content into the card
<app-card>
<h2 card-title>User Profile</h2>
<p>This goes into the default ng-content slot.</p>
</app-card>
The select attribute on <ng-content> uses CSS-selector syntax to allow multiple named slots (multi-slot content projection). This pattern is widely used in UI component libraries.
22 What is the difference between Observable and Promise in Angular? ►
RxJS
- Promise โ resolves once with a single value. Eager (starts immediately). Cannot be cancelled. Native JavaScript.
- Observable โ can emit zero, one, or many values over time. Lazy (starts only when subscribed). Can be cancelled by unsubscribing. Part of RxJS.
// Promise โ resolves once
const p = fetch('/api/users').then(r => r.json());
// Can't cancel, can't retry, no transformation operators
// Observable โ lazy, cancellable, composable
const obs$ = this.http.get<User[]>('/api/users').pipe(
retry(3), // retry on error
debounceTime(300), // wait 300ms
catchError(err => of([])) // handle error
);
In Angular, HttpClient returns Observables. You can convert to a Promise with .toPromise() or firstValueFrom() if needed. For HTTP (single response), both work. Observables are essential for WebSockets, real-time data, and streams.
📝 Knowledge Check
Test your understanding of Angular fundamentals with these five questions.