Angular Interview Questions for Freshers and Mid-Level Developers (With Examples)
12 Angular interview questions with code: components and templates, data binding, standalone components, directives, pipes, services and dependency injection, lifecycle hooks, change detection and OnPush, signals, RxJS observables, routing with guards and lazy loading, and forms.
Angular is a full framework: it includes routing, forms, HTTP, dependency injection and a CLI out of the box, so interviews cover a wide range. This guide answers the 12 Angular interview questions that come up most for fresher-to-mid roles, with short code examples in modern Angular (standalone components and signals).
Components and templates#
Q1. What is an Angular component?#
Answer: a component controls a part of the screen. It has three parts: a TypeScript class (data and logic), an HTML template (view) and styles. The @Component decorator connects them and sets the selector used as a custom HTML tag.
import { Component } from "@angular/core";
@Component({
selector: "app-greeting",
standalone: true,
template: `<h2>Hello, {{ name }}!</h2>`,
styles: [`h2 { color: steelblue; }`],
})
export class GreetingComponent {
name = "Asha";
}Use it in another template as <app-greeting></app-greeting>.
Q2. Explain the types of data binding in Angular#
| Type | Syntax | Direction |
|---|---|---|
| Interpolation | {{ title }} | Class → view |
| Property binding | [disabled]="isSaving" | Class → view |
| Event binding | (click)="save()" | View → class |
| Two-way binding | [(ngModel)]="email" | Both ways |
<input [(ngModel)]="email" placeholder="Email" />
<button [disabled]="!email" (click)="subscribe()">Subscribe</button>
<p>You entered: {{ email }}</p>"Banana in a box" [( )] is shorthand for a property binding plus an event binding.
Q3. How do parent and child components communicate?#
// Child
@Component({
selector: "app-product-card",
standalone: true,
template: `
<h3>{{ product.name }}</h3>
<button (click)="addToCart.emit(product.id)">Add</button>
`,
})
export class ProductCardComponent {
@Input({ required: true }) product!: Product; // data in
@Output() addToCart = new EventEmitter<number>(); // events out
}
// Parent template
// <app-product-card [product]="p" (addToCart)="onAdd($event)" />Answer: parent to child with @Input(), child to parent with @Output() and EventEmitter. Newer Angular also offers signal-based input() and output() functions. Unrelated components share data through a service.
Q4. What are standalone components?#
Answer: standalone components (default since Angular 17) declare their own dependencies in an imports array, so you no longer need an NgModule to declare them. This reduces boilerplate and makes lazy loading individual components easy. Older apps use @NgModule with declarations, imports and providers; both styles can coexist.
Directives and pipes#
Q5. What are directives? Name the types#
- Components: directives with a template.
- Structural directives: change the DOM layout by adding or removing elements, such as
*ngIfand*ngFor. Angular 17+ also has built-in control flow:@if,@forand@switch. - Attribute directives: change the appearance or behaviour of an existing element, such as
ngClass,ngStyleor a custom one.
@if (user) {
<p>Welcome, {{ user.name }}</p>
} @else {
<button (click)="login()">Log in</button>
}
<ul>
@for (item of cart; track item.id) {
<li [class.out-of-stock]="!item.inStock">{{ item.name }}</li>
} @empty {
<li>Your cart is empty</li>
}
</ul>The track expression in @for (like trackBy with *ngFor) lets Angular reuse DOM nodes when the list changes.
Q6. What are pipes? What is the difference between pure and impure pipes?#
@Pipe({ name: "truncate", standalone: true })
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 20): string {
return value.length > limit ? value.slice(0, limit) + "…" : value;
}
}
// Template: {{ description | truncate:50 }}
// {{ price | currency:'INR' }} {{ today | date:'dd MMM yyyy' }}Answer: pipes transform values in templates. A pure pipe (the default) runs only when its input reference changes, so it's cheap. An impure pipe (pure: false) runs on every change detection cycle, which can hurt performance; the built-in async pipe is impure because it must track emitted values.
Services and dependency injection#
Q7. What is dependency injection in Angular?#
Answer: dependency injection (DI) means a class asks for the objects it needs instead of creating them. Angular's injector creates and supplies them. This makes code loosely coupled and easy to test, because you can provide a mock service in tests.
@Injectable({ providedIn: "root" }) // one shared instance (singleton)
export class ProductService {
private http = inject(HttpClient);
getProducts() {
return this.http.get<Product[]>("/api/products");
}
}
@Component({ /* ... */ })
export class ProductListComponent {
private productService = inject(ProductService); // or constructor injection
products$ = this.productService.getProducts();
}providedIn: "root" creates an app-wide singleton and allows tree-shaking if it's unused. Providing a service in a component's providers array creates a separate instance for that component and its children.
Lifecycle and change detection#
Q8. What are the main lifecycle hooks?#
| Hook | When it runs | Typical use |
|---|---|---|
constructor | Class created | Inject dependencies only |
ngOnChanges | An @Input changes | React to new input values |
ngOnInit | Once, after the first ngOnChanges | Fetch data, initial setup |
ngAfterViewInit | After the view and child views are created | Access @ViewChild elements |
ngOnDestroy | Before the component is removed | Unsubscribe, clear timers |
A classic question: why fetch data in ngOnInit and not the constructor? Because inputs aren't set yet in the constructor, and keeping the constructor light makes the class easier to test.
Q9. How does change detection work? What does OnPush do?#
Answer: after events, HTTP responses or timers, Angular checks component bindings and updates the DOM where values changed. Traditionally Zone.js tells Angular when async work finishes. With the Default strategy, Angular checks the whole component tree.
With ChangeDetectionStrategy.OnPush, a component is checked only when:
- an
@Inputreference changes, - an event happens inside it,
- an observable used with the
asyncpipe emits, or a signal it reads changes, - or you call
markForCheck().
@Component({
selector: "app-order-list",
changeDetection: ChangeDetectionStrategy.OnPush,
/* ... */
})
export class OrderListComponent {
@Input() orders: Order[] = []; // replace the array; don't push into it
}OnPush plus immutable data greatly reduces checks in large apps.
Q10. What are signals in Angular?#
@Component({
selector: "app-cart",
standalone: true,
template: `
<p>Items: {{ count() }} | Total: {{ total() | currency:'INR' }}</p>
<button (click)="add({ name: 'Pen', price: 20 })">Add pen</button>
`,
})
export class CartComponent {
items = signal<{ name: string; price: number }[]>([]);
count = computed(() => this.items().length);
total = computed(() => this.items().reduce((s, i) => s + i.price, 0));
constructor() {
effect(() => console.log("Cart changed:", this.count()));
}
add(item: { name: string; price: number }) {
this.items.update((list) => [...list, item]);
}
}Answer: signals are reactive values. You read them by calling them (count()), change them with set or update, derive values with computed, and run side effects with effect. Angular knows exactly which components depend on which signals, enabling fine-grained updates and zoneless change detection.
RxJS, routing and forms#
Q11. What are Observables, and how are they different from Promises?#
| Promise | Observable | |
|---|---|---|
| Values | One | Zero, one or many over time |
| Execution | Eager (starts immediately) | Lazy (starts on subscribe) |
| Cancellable | No | Yes (unsubscribe) |
| Operators | then, catch | map, filter, switchMap, debounceTime and many more |
// Type-ahead search with RxJS
this.results$ = this.searchControl.valueChanges.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((term) => this.api.search(term)) // cancels the previous request
);Avoid memory leaks by using the async pipe in templates (it unsubscribes automatically) or takeUntilDestroyed(). Know the difference between switchMap (cancel previous), mergeMap (run in parallel), concatMap (queue in order) and exhaustMap (ignore new until done).
Q12. How do routing, guards, lazy loading and forms work?#
export const routes: Routes = [
{ path: "", component: HomeComponent },
{
path: "admin",
canActivate: [authGuard], // route guard
loadComponent: () =>
import("./admin/admin.component").then((m) => m.AdminComponent), // lazy loaded
},
{ path: "products/:id", component: ProductDetailComponent },
{ path: "**", component: NotFoundComponent },
];
export const authGuard: CanActivateFn = () => {
const auth = inject(AuthService);
return auth.isLoggedIn() ? true : inject(Router).parseUrl("/login");
};Routing: routes map URLs to components; <router-outlet> shows the active one. Guards such as canActivate and canDeactivate control navigation. Lazy loading downloads a feature's code only when its route is visited.
Forms: template-driven forms use ngModel in the template and suit simple forms. Reactive forms define the model in the class with FormGroup, FormControl and validators; they're more testable and better for complex, dynamic forms.
form = new FormGroup({
email: new FormControl("", [Validators.required, Validators.email]),
password: new FormControl("", [Validators.required, Validators.minLength(8)]),
});Quick revision#
| Concept | Remember |
|---|---|
| Component | Class + template + styles, with a selector |
| Data binding | {{ }}, [prop], (event), [(ngModel)] |
| Directives | Structural (@if, @for) and attribute (ngClass) |
| DI | @Injectable({ providedIn: "root" }) + inject() |
| Lifecycle | Fetch in ngOnInit, clean up in ngOnDestroy |
| OnPush | Check only on new inputs, events, async pipe or signals |
| Signals | signal, computed, effect |
| RxJS | switchMap cancels; use async pipe to unsubscribe |
Comparing frameworks? See Vue.js interview questions and React hooks interview questions.
Key takeaways#
- Angular apps are built from components, directives, pipes and injectable services.
- Know all four binding types and how
@Input/@Outputconnect components. - Dependency injection supplies services;
providedIn: "root"gives a singleton. - OnPush and signals make change detection faster and more predictable.
- Use RxJS operators like
switchMapcarefully, and unsubscribe with theasyncpipe ortakeUntilDestroyed.