Angular Interview Questions - Routing, Forms & Performance (91-120)
Master Angular routing, forms, and performance optimization for FAANG interviews with practical examples.
Master Angular routing, forms, and performance optimization for FAANG interviews with practical examples. This interview-focused guide covers essential angular interview questions - routing, forms & performance (91-120) concepts for technical interviews.
Angular Interview Questions - Routing, Forms & Performance (91-120)
Question 91: What is Angular Router?
Angular Router is a service that enables navigation from one view to another as users perform application tasks!
Question 92: How to Configure Angular Routing (Standalone)?
// app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './home.component';
import { AboutComponent } from './about.component';
export const routes: Routes = [
{ path: '', component: HomeComponent }, // Default route
{ path: 'about', component: AboutComponent }, // /about
{ path: '**', redirectTo: '' } // Wildcard route (404)
];
// app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes) // <-- Provide router
]
};
// app.component.html
<nav>
<a routerLink="/" routerLinkActive="active">Home</a>
<a routerLink="/about" routerLinkActive="active">About</a>
</nav>
<router-outlet></router-outlet> <!-- Where routed components render! -->
Question 93: What is routerLink and routerLinkActive?
routerLink: Directive to navigate between routes (like<a routerLink="/about">)routerLinkActive: Directive that adds CSS classes when the link is active!
Question 94: How to Navigate Programmatically?
Use Router service!
import { Component } from '@angular/core';
import { Router } from '@angular/router';
@Component({ template: '<button (click)="goHome()">Go Home</button>', standalone: true })
export class SomeComponent {
constructor(private router: Router) {}
goHome() {
this.router.navigate(['/']); // Navigate by path array
// OR
this.router.navigateByUrl('/'); // Navigate by URL string
}
}
Question 95: What are Route Parameters?
Route parameters let you pass data in the URL (like /users/123)!
Example:
// Routes
const routes: Routes = [
{ path: 'users/:id', component: UserDetailComponent }
];
// Component
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
@Component({ template: 'User ID: {{ userId }}', standalone: true })
export class UserDetailComponent implements OnInit {
userId!: string | null;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// Snapshot (one-time value)
this.userId = this.route.snapshot.paramMap.get('id');
// OR Observable (reacts to changes)
this.route.paramMap.subscribe((params: ParamMap) => {
this.userId = params.get('id');
});
}
}
Question 96: What are Query Parameters and Fragments?
- Query params:
?sort=asc&page=2 - Fragment:
#section1
Usage:
// Get query params
this.route.snapshot.queryParamMap.get('sort');
// Navigate with query params
this.router.navigate(['/users'], { queryParams: { page: 1 }, fragment: 'top' });
Question 97: What are Child Routes?
Child routes let you nest routes! Use children array!
const routes: Routes = [
{
path: 'products',
component: ProductsComponent,
children: [
{ path: '', component: ProductListComponent },
{ path: ':id', component: ProductDetailComponent }
]
}
];
// products.component.html
<h1>Products</h1>
<router-outlet></router-outlet> <!-- Child outlet! -->
Question 98: What are Route Guards?
Route guards are interfaces that let you control navigation (allow/deny access, pre-fetch data, etc.)!
| Guard | Purpose |
|---|---|
CanActivate | Guard navigation to a route |
CanActivateChild | Guard navigation to child routes |
CanDeactivate | Guard navigation away from current route |
Resolve | Pre-fetch data before route activation |
CanLoad | Guard lazy loading of feature modules |
Question 99: What is a CanActivate Guard Example?
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.authService.isLoggedIn) {
return true;
}
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
// Use in routes
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
];
Question 100: What is Lazy Loading in Angular?
Lazy loading is a technique that loads feature modules only when they are needed (reduces initial bundle size)!
Example (Standalone Routes):
const routes: Routes = [
{
path: 'admin',
loadChildren: () => import('./admin/admin.routes').then(m => m.ADMIN_ROUTES)
}
];
Question 101: What are Angular Forms?
Angular provides two approaches to forms:
- Template-Driven Forms: Simple, logic in template, good for small forms
- Reactive Forms: More scalable, logic in component, better for complex forms
Question 102: What are Template-Driven Forms?
Use ngModel and FormsModule!
import { Component } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-template-form',
template: `
<form #f="ngForm" (ngSubmit)="onSubmit(f)">
<input name="email" ngModel required email>
<input name="password" ngModel required minlength="6">
<button type="submit" [disabled]="f.invalid">Submit</button>
</form>
`,
standalone: true,
imports: [FormsModule, CommonModule]
})
export class TemplateFormComponent {
onSubmit(form: NgForm) {
console.log(form.value);
}
}
Question 103: What are Reactive Forms?
Reactive forms use FormGroup, FormControl, FormArray, and ReactiveFormsModule! Logic is in component class!
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-reactive-form',
template: `
<form [formGroup]="loginForm" (ngSubmit)="onSubmit()">
<input formControlName="email">
<div *ngIf="loginForm.get('email')?.invalid && loginForm.get('email')?.touched">
Email is required and must be valid!
</div>
<input formControlName="password" type="password">
<button type="submit" [disabled]="loginForm.invalid">Submit</button>
</form>
`,
standalone: true,
imports: [ReactiveFormsModule, CommonModule]
})
export class ReactiveFormComponent {
loginForm: FormGroup;
constructor(private fb: FormBuilder) {
this.loginForm = this.fb.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]]
});
}
onSubmit() {
console.log(this.loginForm.value);
}
}
Question 104: What is FormBuilder?
FormBuilder is a service that provides syntactic sugar to create FormGroup, FormControl, and FormArray more concisely!
Question 105: What are Form Validators?
Validators ensure form values meet certain criteria! Angular provides built-in validators (required, email, minLength, etc.) and you can create custom ones!
Custom Validator:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function forbiddenNameValidator(name: string): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const forbidden = control.value === name;
return forbidden ? { 'forbiddenName': { value: control.value } } : null;
};
}
// Use in form
this.loginForm = this.fb.group({
username: ['', [Validators.required, forbiddenNameValidator('admin')]]
});
Question 106: What is FormArray?
FormArray is a form control that manages an array of FormControl, FormGroup, or FormArray! Great for dynamic forms!
import { Component } from '@angular/core';
import { FormBuilder, FormArray, ReactiveFormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-form-array',
template: `
<form [formGroup]="orderForm" (ngSubmit)="onSubmit()">
<div formArrayName="items">
<div *ngFor="let item of items.controls; let i = index" [formGroupName]="i">
<input formControlName="name">
<input formControlName="quantity" type="number">
<button (click)="removeItem(i)">Remove</button>
</div>
</div>
<button (click)="addItem()">Add Item</button>
<button type="submit">Submit</button>
</form>
`,
standalone: true,
imports: [ReactiveFormsModule, CommonModule]
})
export class FormArrayComponent {
orderForm = this.fb.group({
items: this.fb.array([
this.fb.group({ name: '', quantity: 1 })
])
});
constructor(private fb: FormBuilder) {}
get items(): FormArray {
return this.orderForm.get('items') as FormArray;
}
addItem() {
this.items.push(this.fb.group({ name: '', quantity: 1 }));
}
removeItem(i: number) {
this.items.removeAt(i);
}
onSubmit() {
console.log(this.orderForm.value);
}
}
Question 107: What is Angular Performance Optimization?
Key techniques:
- Use
ChangeDetectionStrategy.OnPush - Use
asyncpipe - Lazy load modules/components
- Use
trackBywith*ngFor - Avoid heavy computations in templates
- Use
purepipes - Optimize bundle size (tree shaking, lazy loading)
- Use
@defer(Angular 17+) for deferred views - Unsubscribe from Observables
Question 108: What is @defer in Angular (17+)?
@defer lets you defer loading of components/parts of your app until a trigger event! Great for performance!
Example:
<!-- Defer until viewport -->
@defer (on viewport) {
<app-heavy-component></app-heavy-component>
} @loading {
<p>Loading...</p>
} @placeholder {
<p>Placeholder (visible immediately)</p>
} @error {
<p>Oops, something went wrong!</p>
}
<!-- Defer on interaction -->
<button #trigger>Load Component</button>
@defer (on interaction(trigger)) {
<app-chart></app-chart>
}
Question 109: What is Angular Universal (Server-Side Rendering - SSR)?
Angular Universal renders Angular apps on the server to send fully rendered pages to the client! Improves initial load time and SEO!
Question 110: What is Pre-Rendering (SSG)?
Pre-rendering (Static Site Generation) generates static HTML files at build time! Great for static content!
Question 111: What is Tree Shaking?
Tree shaking removes unused code from the bundle! Enabled by default in production builds!
Question 112: What is AOT Compilation?
AOT (Ahead-of-Time) compilation compiles your Angular app at build time instead of runtime! Faster startup, smaller bundle sizes! (Enabled by default in ng build --prod)
Question 113: What is JIT Compilation?
JIT (Just-in-Time) compiles your app in the browser at runtime! Used during development (ng serve)!
Question 114: How to Optimize Bundle Size?
- Lazy load modules/routes
- Use
@defer - Tree shaking (AOT)
- Analyze bundle with
webpack-bundle-analyzer - Remove unused dependencies
- Use smaller libraries where possible
Question 115: What is webpack-bundle-analyzer?
It's a tool that visualizes your bundle to help you see what's taking up space!
Question 116: What is zone.js?
zone.js is a library that helps Angular intercept async operations (events, HTTP, timers, etc.) to run change detection!
Question 117: What is Zone-less Angular (Noop Zone)?
You can run Angular without zone.js (Angular 16+). Gives you full control over change detection with ChangeDetectorRef!
Question 118: What are Angular Signals (Angular 16+)?
Signals are a new primitive for reactive state in Angular! They are a simpler alternative to RxJS for local state!
Example:
import { Component, signal, computed } from '@angular/core';
@Component({
selector: 'app-signals',
template: `
<p>Count: {{ count() }}</p>
<p>Double: {{ double() }}</p>
<button (click)="increment()">+</button>
`,
standalone: true
})
export class SignalsComponent {
count = signal(0);
double = computed(() => this.count() * 2);
increment() {
this.count.update(val => val + 1);
}
}
Question 119: What is computed() and effect() with Signals?
computed(): Derived value that re-calculates when its dependencies changeeffect(): Runs side effects when signals it depends on change
Question 120: What is Angular 17+ Control Flow Syntax?
Angular 17 introduces new built-in control flow syntax as an alternative to structural directives!
<!-- New @if -->
@if (isLoggedIn) {
<p>Welcome back!</p>
} @else {
<p>Please log in!</p>
}
<!-- New @for -->
@for (product of products; track product.id) {
<li>{{ product.name }}</li>
} @empty {
<p>No products!</p>
}
<!-- New @switch -->
@switch (status) {
@case ('pending') { <p>Pending</p> }
@case ('approved') { <p>Approved</p> }
@default { <p>Unknown</p> }
}