Angular45 min read

Angular Interview Questions: 50 Essential Questions for Developers

Comprehensive collection of 50 essential Angular interview questions covering components, services, routing, directives, and Angular best practices.

Lisa Anderson
December 16, 2025
0.0k0

This comprehensive guide covers 50 essential Angular interview questions that every Angular developer should know. These questions cover fundamental concepts, components, services, routing, directives, dependency injection, and Angular best practices commonly asked in technical interviews.

Core Angular Concepts

Understanding Angular's core concepts is essential. These questions test your knowledge of components, modules, services, and the Angular architecture.

Components & Templates

Components are building blocks of Angular applications. Master these questions to demonstrate your understanding of component lifecycle, data binding, and template syntax.

Services & Dependency Injection

Services provide shared functionality across components. These questions cover dependency injection, services, singletons, and how Angular manages dependencies.

Routing & Navigation

Angular Router enables navigation between views. These questions cover routing configuration, guards, lazy loading, and navigation patterns.

Directives & Pipes

Directives modify DOM, pipes transform data. These questions cover built-in and custom directives, pipes, and when to use each.

Advanced Angular

Advanced topics include change detection, RxJS, forms, HTTP, and performance optimization. These questions test your deep understanding of Angular.

#Angular#Interview#Components#Services#Routing

Common Questions & Answers

Q1

What is Angular?

A

Angular is TypeScript-based web framework for building single-page applications (SPAs). Features: component-based architecture, dependency injection, routing, two-way data binding, directives, services, RxJS for reactive programming. Developed by Google.

Q2

What is the difference between AngularJS and Angular?

A

AngularJS (v1.x) uses JavaScript, controllers, scope, two-way binding. Angular (v2+) uses TypeScript, components, no scope, one-way binding by default, better performance, mobile support, modern architecture. Angular is complete rewrite, not upgrade.

typescript
// AngularJS (v1)
app.controller('MyCtrl', function($scope) {
  $scope.name = 'John';
});

// Angular (v2+)
@Component({
  selector: 'app-root',
  template: '<h1>{{name}}</h1>'
})
export class AppComponent {
  name = 'John';
}
Q3

What is a component in Angular?

A

Component is building block of Angular app. Consists of: class (TypeScript), template (HTML), styles (CSS), metadata (@Component decorator). Encapsulates data, logic, and view. Reusable, composable. Root component bootstraps application.

typescript
import { Component } from '@angular/core';

@Component({
  selector: 'app-user',
  template: '<h1>{{name}}</h1>',
  styleUrls: ['./user.component.css']
})
export class UserComponent {
  name = 'John Doe';
}
Q4

What is a module in Angular?

A

Module (@NgModule) organizes application into cohesive blocks. Declares components, directives, pipes. Imports other modules. Exports for other modules. Provides services. Root module (AppModule) bootstraps app. Feature modules organize by feature.

typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Q5

What is data binding in Angular?

A

Data binding connects component data with template. Types: interpolation {{ }}, property binding [ ], event binding ( ), two-way binding [( )]. One-way by default (component to view). Two-way requires FormsModule. Enables dynamic UI updates.

typescript
// Interpolation
<h1>{{title}}</h1>

// Property binding
<img [src]="imageUrl">
<button [disabled]="isDisabled">

// Event binding
<button (click)="handleClick()">Click</button>

// Two-way binding
<input [(ngModel)]="name">
Q6

What is a directive?

A

Directive modifies DOM or component behavior. Types: component (with template), structural (*ngIf, *ngFor), attribute ([ngClass], [ngStyle]). Structural directives change DOM structure. Attribute directives change appearance/behavior. Can create custom directives.

typescript
// Structural directive
<div *ngIf="isVisible">Content</div>
<li *ngFor="let item of items">{{item}}</li>

// Attribute directive
<div [ngClass]="{'active': isActive}">Content</div>
<div [ngStyle]="{'color': textColor}">Content</div>

// Custom directive
@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective { }
Q7

What is a service in Angular?

A

Service is class with specific purpose, provides functionality to components. Injectable via dependency injection. Singleton by default (one instance per injector). Uses: data fetching, business logic, shared state, logging. Created with @Injectable decorator.

typescript
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  getUsers() {
    return ['John', 'Jane', 'Bob'];
  }
}

// Inject in component
constructor(private userService: UserService) { }
Q8

What is dependency injection?

A

Dependency injection provides dependencies to classes rather than creating them. Angular creates and manages instances. Benefits: testability, maintainability, loose coupling. Inject via constructor. Configure in providers array or providedIn: root.

typescript
// Service
@Injectable({
  providedIn: 'root'
})
export class DataService { }

// Component
@Component({...})
export class MyComponent {
  constructor(private dataService: DataService) { }
  // Angular injects DataService instance
}
Q9

What is routing in Angular?

A

Routing enables navigation between views. Configure routes in Routes array. RouterModule provides router directives and service. Use routerLink for navigation, router-outlet for displaying routed components. Supports lazy loading, guards, parameters.

typescript
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Q10

What are Angular lifecycle hooks?

A

Lifecycle hooks are methods called at specific points in component lifecycle. Order: ngOnChanges, ngOnInit, ngDoCheck, ngAfterContentInit, ngAfterContentChecked, ngAfterViewInit, ngAfterViewChecked, ngOnDestroy. Implement OnInit, OnDestroy most commonly.

typescript
import { Component, OnInit, OnDestroy } from '@angular/core';

@Component({...})
export class MyComponent implements OnInit, OnDestroy {
  ngOnInit() {
    // Called after first ngOnChanges
    // Initialize component
  }
  
  ngOnDestroy() {
    // Called before component destruction
    // Cleanup subscriptions, timers
  }
}
Q11

What is the difference between constructor and ngOnInit?

A

Constructor runs when class is instantiated, before Angular processes. ngOnInit runs after Angular sets up component (after first ngOnChanges). Use constructor for dependency injection. Use ngOnInit for initialization logic, data fetching.

typescript
export class MyComponent implements OnInit {
  constructor(private service: DataService) {
    // DI happens here
    // Don't access @Input properties here
  }
  
  ngOnInit() {
    // Component initialized
    // @Input properties available
    // Safe to fetch data
    this.service.getData();
  }
}
Q12

What is *ngIf and *ngFor?

A

*ngIf conditionally renders element (adds/removes from DOM). *ngFor repeats element for each item in array. Both are structural directives. *ngIf: show/hide. *ngFor: iterate. Use trackBy with *ngFor for performance.

typescript
// *ngIf
<div *ngIf="isLoggedIn">Welcome!</div>
<div *ngIf="user; else noUser">{{user.name}}</div>
<ng-template #noUser>No user</ng-template>

// *ngFor
<ul>
  <li *ngFor="let item of items; trackBy: trackById">
    {{item.name}}
  </li>
</ul>

trackById(index: number, item: any): any {
  return item.id;
}
Q13

What is a pipe?

A

Pipe transforms data in template. Syntax: {{ value | pipeName:arg1:arg2 }}. Built-in: date, currency, uppercase, lowercase, json, async. Can create custom pipes. Pure pipes (default) only run when input changes. Impure pipes run on every change detection.

typescript
// Built-in pipes
{{ name | uppercase }}
{{ price | currency:'USD' }}
{{ date | date:'short' }}
{{ data | json }}

// Custom pipe
@Pipe({ name: 'reverse' })
export class ReversePipe implements PipeTransform {
  transform(value: string): string {
    return value.split('').reverse().join('');
  }
}
Q14

What is @Input and @Output?

A

@Input allows parent to pass data to child component. @Output allows child to emit events to parent. Parent-child communication. @Input: property binding. @Output: event binding. Enables component composition.

typescript
// Child component
@Component({...})
export class ChildComponent {
  @Input() name: string;
  @Output() clicked = new EventEmitter<void>();
  
  onClick() {
    this.clicked.emit();
  }
}

// Parent template
<app-child [name]="parentName" (clicked)="handleClick()"></app-child>
Q15

What is ViewChild and ViewChildren?

A

ViewChild accesses child component/directive/element in template. ViewChildren accesses multiple. Use @ViewChild decorator. Access after ngAfterViewInit. Use for: accessing child methods, DOM manipulation, component communication.

typescript
import { ViewChild, ElementRef, AfterViewInit } from '@angular/core';

@Component({...})
export class ParentComponent implements AfterViewInit {
  @ViewChild('myInput') input: ElementRef;
  @ViewChild(ChildComponent) child: ChildComponent;
  
  ngAfterViewInit() {
    this.input.nativeElement.focus();
    this.child.doSomething();
  }
}

// Template
<input #myInput>
<app-child></app-child>
Q16

What is lazy loading?

A

Lazy loading loads modules on-demand when route is accessed. Reduces initial bundle size, improves startup time. Configure with loadChildren in routes. Module loaded asynchronously. Use for feature modules, not core modules.

typescript
const routes: Routes = [
  {
    path: 'admin',
    loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
  }
];

// AdminModule must not be imported in AppModule
Q17

What are route guards?

A

Route guards control navigation. Types: CanActivate (can access route), CanDeactivate (can leave route), Resolve (pre-fetch data), CanLoad (can load module). Implement interface, return boolean or Observable<boolean>. Use for authentication, authorization.

typescript
@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(): boolean {
    if (this.authService.isLoggedIn()) {
      return true;
    }
    this.router.navigate(['/login']);
    return false;
  }
}

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }
];
Q18

What is RxJS?

A

RxJS is reactive programming library using Observables. Angular uses for HTTP, routing, forms. Observable represents async data stream. Operators transform streams (map, filter, switchMap). Subscribe to receive values. Unsubscribe to prevent memory leaks.

typescript
import { Observable } from 'rxjs';
import { map, filter } from 'rxjs/operators';

this.http.get('/api/users').pipe(
  map(users => users.filter(u => u.active)),
  map(users => users.length)
).subscribe(count => {
  console.log(count);
});
Q19

What is the difference between Observable and Promise?

A

Observable: multiple values, lazy (executes on subscribe), cancellable, operators. Promise: single value, eager (executes immediately), not cancellable. Observable: streams, HTTP, events. Promise: one-time async operations. Observable more powerful.

typescript
// Promise
const promise = fetch('/api/data').then(r => r.json());
promise.then(data => console.log(data));

// Observable
const observable = this.http.get('/api/data');
observable.subscribe(data => console.log(data));
observable.pipe(map(d => d.items)).subscribe(items => console.log(items));
Q20

What is change detection?

A

Change detection checks for data changes and updates view. Default strategy: checks all components on every event. OnPush strategy: checks only when @Input changes or events from component. Improves performance. Use OnPush for better performance.

typescript
// Default change detection
@Component({
  selector: 'app-default',
  // Checks on every event
})

// OnPush change detection
@Component({
  selector: 'app-onpush',
  changeDetection: ChangeDetectionStrategy.OnPush
  // Only checks when @Input changes
})
Q21

What are reactive forms?

A

Reactive forms are model-driven, programmatic approach. FormBuilder creates FormGroup/FormControl. Validators for validation. More testable, scalable. Use for complex forms, dynamic forms. Import ReactiveFormsModule.

typescript
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

export class MyComponent {
  form: FormGroup;
  
  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]]
    });
  }
  
  onSubmit() {
    if (this.form.valid) {
      console.log(this.form.value);
    }
  }
}
Q22

What are template-driven forms?

A

Template-driven forms use ngModel, directives in template. Simpler, less code. Two-way binding. Less testable, less control. Use for simple forms. Import FormsModule. Validation via template directives.

typescript
import { FormsModule } from '@angular/forms';

// Template
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
  <input name="name" ngModel required #name="ngModel">
  <div *ngIf="name.invalid">Name required</div>
  
  <input name="email" ngModel email>
  <button type="submit">Submit</button>
</form>
Q23

What is HTTP Interceptor?

A

HTTP Interceptor intercepts HTTP requests/responses. Use for: adding headers (auth tokens), logging, error handling, transforming requests/responses. Implement HttpInterceptor interface. Provide in HTTP_INTERCEPTORS. Multiple interceptors form chain.

typescript
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const token = this.authService.getToken();
    const cloned = req.clone({
      setHeaders: { Authorization: `Bearer ${token}` }
    });
    return next.handle(cloned);
  }
}

// Provide in module
providers: [
  { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
]
Q24

What is the difference between ng-container and ng-template?

A

ng-container: grouping element, not rendered in DOM. ng-template: template that is not rendered until used. ng-container: wrapper without extra element. ng-template: reusable template, used with *ngIf else, *ngFor, ViewChild.

typescript
// ng-container - no DOM element
<ng-container *ngIf="condition">
  <div>Content</div>
</ng-container>

// ng-template - reusable template
<ng-template #myTemplate>
  <div>Template content</div>
</ng-template>

<div *ngIf="show; else myTemplate">Visible</div>
Q25

What is ContentChild and ContentChildren?

A

ContentChild accesses projected content (ng-content). ContentChildren accesses multiple. Use @ContentChild decorator. Access after ngAfterContentInit. Use for: accessing projected components, component communication, content projection patterns.

typescript
// Parent
@Component({...})
export class ParentComponent {
  @ContentChild(ChildComponent) child: ChildComponent;
  
  ngAfterContentInit() {
    this.child.doSomething();
  }
}

// Template
<app-parent>
  <app-child></app-child>  <!-- Projected content -->
</app-parent>
Q26

What is content projection?

A

Content projection inserts content from parent into child component. Use <ng-content> in child template. Single slot or multiple slots with select attribute. Enables flexible, reusable components. Similar to React children prop.

typescript
// Child component
@Component({
  selector: 'app-card',
  template: `
    <div class="card">
      <ng-content select="[header]"></ng-content>
      <ng-content></ng-content>
      <ng-content select="[footer]"></ng-content>
    </div>
  `
})

// Parent template
<app-card>
  <div header>Title</div>
  <p>Body content</p>
  <div footer>Footer</div>
</app-card>
Q27

What is the difference between providedIn root and providers array?

A

providedIn: root makes service singleton across entire app, tree-shakeable. providers array in module makes service available to that module and children. providedIn: root preferred (tree-shaking, simpler). providers: module-level scope.

typescript
// Tree-shakeable singleton
@Injectable({
  providedIn: 'root'
})
export class MyService { }

// Module-level
@NgModule({
  providers: [MyService]
})
export class MyModule { }
Q28

What is async pipe?

A

Async pipe subscribes to Observable/Promise, displays value, unsubscribes automatically. Prevents memory leaks. Handles null/undefined. Use in template: {{ observable$ | async }}. Automatically manages subscription lifecycle.

typescript
// Component
export class MyComponent {
  users$ = this.http.get<User[]>('/api/users');
}

// Template
<ul>
  <li *ngFor="let user of users$ | async">
    {{user.name}}
  </li>
</ul>

// Automatically subscribes/unsubscribes
Q29

What is trackBy in *ngFor?

A

trackBy function identifies items in *ngFor for efficient DOM updates. Prevents unnecessary re-rendering. Returns unique identifier. Improves performance with large lists. Use when list items change frequently.

typescript
// Component
trackByUserId(index: number, user: User): any {
  return user.id;
}

// Template
<li *ngFor="let user of users; trackBy: trackByUserId">
  {{user.name}}
</li>

// Angular tracks by user.id instead of index
Q30

What is the difference between ngOnInit and constructor?

A

Constructor: class instantiation, dependency injection, before Angular processing. ngOnInit: after Angular initialization, @Input properties available, safe for data fetching. Use constructor for DI, ngOnInit for initialization.

typescript
export class MyComponent implements OnInit {
  @Input() data: any;
  
  constructor(private service: DataService) {
    // this.data is undefined here
    // DI happens here
  }
  
  ngOnInit() {
    // this.data is available here
    // Safe to use service
    this.service.fetchData();
  }
}
Q31

What is Subject in RxJS?

A

Subject is Observable and Observer. Can emit values, subscribe to values. Types: Subject (no initial value), BehaviorSubject (has current value), ReplaySubject (replays n values), AsyncSubject (emits last value on complete). Use for component communication.

typescript
import { Subject, BehaviorSubject } from 'rxjs';

// Subject
const subject = new Subject<string>();
subject.subscribe(v => console.log(v));
subject.next('Hello');

// BehaviorSubject
const behaviorSubject = new BehaviorSubject<string>('Initial');
behaviorSubject.subscribe(v => console.log(v)); // 'Initial'
behaviorSubject.next('New');
Q32

What is ActivatedRoute?

A

ActivatedRoute provides route information. Access route params, query params, data. Observable properties for reactive access. Use for: getting route parameters, query strings, route data. Inject Router, ActivatedRoute.

typescript
import { ActivatedRoute } from '@angular/router';

export class MyComponent {
  constructor(private route: ActivatedRoute) {
    // Snapshot (one-time)
    const id = this.route.snapshot.params['id'];
    
    // Observable (reactive)
    this.route.params.subscribe(params => {
      console.log(params['id']);
    });
  }
}
Q33

What is the difference between declarations, imports, and exports in NgModule?

A

declarations: components, directives, pipes belonging to this module. imports: other modules to use. exports: components, directives, pipes available to other modules. declarations: local. imports: dependencies. exports: public API.

typescript
@NgModule({
  declarations: [MyComponent, MyDirective], // Local
  imports: [CommonModule, FormsModule],      // Dependencies
  exports: [MyComponent],                    // Public API
  providers: [MyService]
})
export class MyModule { }
Q34

What is OnPush change detection strategy?

A

OnPush strategy checks component only when: @Input reference changes, component emits event, async pipe receives value, manual change detection. Improves performance by reducing checks. Use for: performance optimization, large applications.

typescript
@Component({
  selector: 'app-onpush',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: '<div>{{data}}</div>'
})
export class OnPushComponent {
  @Input() data: any;
  // Only checks when @Input reference changes
}
Q35

What is the difference between reactive and template-driven forms?

A

Reactive: model-driven, FormBuilder, programmatic, more control, testable, scalable. Template-driven: ngModel, template-based, simpler, less control, less testable. Reactive: complex forms. Template-driven: simple forms.

typescript
// Reactive
this.form = this.fb.group({
  name: ['', Validators.required]
});

// Template-driven
<input name="name" [(ngModel)]="name" required>
Q36

What is router-outlet?

A

router-outlet is directive that displays routed component. Place in template where routed views should appear. Angular replaces with component matching route. Can have named outlets for multiple views. Primary outlet is default.

typescript
// App component template
<nav>
  <a routerLink="/home">Home</a>
  <a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>

// Named outlet
<router-outlet name="sidebar"></router-outlet>
Q37

What is routerLink?

A

routerLink directive navigates to route. Use in template: <a routerLink="/path">. Can use array: [routerLink]="['/path', id]". Active link styling with routerLinkActive. Programmatic navigation with Router.navigate().

typescript
// Template
<a routerLink="/home">Home</a>
<a [routerLink]="['/user', userId]">User</a>
<a routerLink="/about" routerLinkActive="active">About</a>

// Programmatic
this.router.navigate(['/home']);
this.router.navigate(['/user', this.userId]);
Q38

What is the difference between Observable and Subject?

A

Observable: unicast (each subscriber gets own execution), lazy. Subject: multicast (shares execution), can emit values. Observable: data producer. Subject: both producer and consumer. Use Subject for component communication, Observable for HTTP.

typescript
// Observable - unicast
const obs = new Observable(observer => {
  observer.next(Math.random());
});
obs.subscribe(v => console.log(v)); // Different values
obs.subscribe(v => console.log(v));

// Subject - multicast
const subj = new Subject();
subj.subscribe(v => console.log(v));
subj.subscribe(v => console.log(v));
subj.next(42); // Both get 42
Q39

What is ng-content?

A

ng-content projects parent content into child component. Single slot or multiple with select attribute. Enables flexible component composition. Similar to React children. Use for: wrapper components, layout components, reusable UI.

typescript
// Child
@Component({
  selector: 'app-wrapper',
  template: '<div class="wrapper"><ng-content></ng-content></div>'
})

// Parent
<app-wrapper>
  <p>Projected content</p>
</app-wrapper>
Q40

What is the difference between ngIf and hidden?

A

*ngIf removes/adds element from DOM. [hidden] keeps element in DOM, hides with CSS. *ngIf: better for performance (no rendering), conditionally create components. [hidden]: faster toggle, element always in DOM. Use *ngIf when condition rarely changes.

typescript
// ngIf - removes from DOM
<div *ngIf="isVisible">Content</div>

// hidden - CSS display: none
<div [hidden]="!isVisible">Content</div>
Q41

What is HttpClient?

A

HttpClient provides HTTP client for making requests. Returns Observables. Methods: get, post, put, delete, patch. Configure with interceptors. Handle errors with catchError. Use async pipe or subscribe. Import HttpClientModule.

typescript
import { HttpClient } from '@angular/common/http';

export class MyService {
  constructor(private http: HttpClient) {}
  
  getUsers() {
    return this.http.get<User[]>('/api/users');
  }
  
  createUser(user: User) {
    return this.http.post<User>('/api/users', user);
  }
}
Q42

What is the difference between map and switchMap?

A

map transforms emitted values. switchMap maps to Observable, switches to latest, cancels previous. map: synchronous transformation. switchMap: async transformation, cancels previous requests. Use switchMap for HTTP in HTTP, prevents race conditions.

typescript
// map - transform value
obs.pipe(map(x => x * 2)).subscribe(v => console.log(v));

// switchMap - switch to new Observable
this.route.params.pipe(
  switchMap(params => this.http.get(`/api/users/${params.id}`))
).subscribe(user => console.log(user));
// Cancels previous request if params change
Q43

What is takeUntil operator?

A

takeUntil completes Observable when another Observable emits. Use for unsubscribing. Prevents memory leaks. Pattern: create Subject, takeUntil in pipe, emit in ngOnDestroy. Better than manual unsubscribe.

typescript
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

export class MyComponent implements OnDestroy {
  private destroy$ = new Subject<void>();
  
  ngOnInit() {
    this.service.getData()
      .pipe(takeUntil(this.destroy$))
      .subscribe(data => console.log(data));
  }
  
  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
Q44

What is the difference between BehaviorSubject and Subject?

A

BehaviorSubject has current value, new subscribers get latest value immediately. Subject has no initial value, subscribers only get future values. BehaviorSubject: state management, current value needed. Subject: event streams.

typescript
// Subject
const subject = new Subject();
subject.subscribe(v => console.log(v)); // Nothing yet
subject.next('A'); // Logs 'A'

// BehaviorSubject
const behavior = new BehaviorSubject('Initial');
behavior.subscribe(v => console.log(v)); // Logs 'Initial' immediately
behavior.next('A'); // Logs 'A'
Q45

What is custom validator?

A

Custom validator is function that validates form control. Returns ValidationErrors or null. Can be sync or async. Use Validators.compose for multiple. Apply in FormControl or template. Use for: complex validation, business rules.

typescript
// Custom validator
function ageValidator(control: AbstractControl): ValidationErrors | null {
  const age = control.value;
  if (age < 18) {
    return { tooYoung: true };
  }
  return null;
}

// Use in reactive form
this.form = this.fb.group({
  age: ['', [Validators.required, ageValidator]]
});
Q46

What is the difference between forRoot and forChild?

A

forRoot configures module with providers (singleton services). forChild configures without providers (shared module). Use forRoot in root/feature module once. Use forChild in feature modules. Prevents duplicate service instances.

typescript
// Root module
imports: [RouterModule.forRoot(routes)]

// Feature module
imports: [RouterModule.forChild(featureRoutes)]

// Shared module
static forRoot() {
  return {
    ngModule: SharedModule,
    providers: [SharedService]
  };
}
Q47

What is Angular CLI?

A

Angular CLI is command-line tool for Angular development. Commands: ng new (create app), ng generate (components, services), ng build (compile), ng serve (dev server), ng test (testing). Simplifies development workflow, enforces best practices.

bash
# Create new app
ng new my-app

# Generate component
ng generate component user
ng g c user

# Build
ng build --prod

# Serve
ng serve

# Test
ng test
Q48

What is the difference between ng serve and ng build?

A

ng serve: development server, live reload, source maps, not optimized. ng build: production build, optimized, minified, tree-shaken, AOT compilation. ng serve: development. ng build: deployment. Use --prod flag for production build.

bash
# Development
ng serve
# Serves on http://localhost:4200
# Live reload enabled

# Production build
ng build --prod
# Creates optimized dist/ folder
# Minified, tree-shaken, AOT compiled
Q49

What is AOT compilation?

A

AOT (Ahead-of-Time) compiles templates at build time. JIT (Just-in-Time) compiles at runtime. AOT: faster startup, smaller bundle, template errors at build, better security. JIT: faster builds, larger bundle. Production uses AOT by default.

bash
// AOT - compile at build
ng build --prod
// Templates compiled to JavaScript
// Errors caught at build time

// JIT - compile at runtime
ng serve
// Templates compiled in browser
// Slower initial load
Q50

What are Angular best practices?

A

Best practices: use OnPush change detection, lazy load modules, unsubscribe Observables, use trackBy in *ngFor, avoid memory leaks, use async pipe, implement interfaces, use TypeScript strict mode, follow style guide, use Angular CLI, optimize bundle size, use interceptors for common logic.

typescript
// Best practices
@Component({
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComponent implements OnInit, OnDestroy {
  private destroy$ = new Subject();
  
  data$ = this.service.getData();
  
  ngOnInit() {
    this.service.getData()
      .pipe(takeUntil(this.destroy$))
      .subscribe();
  }
  
  ngOnDestroy() {
    this.destroy$.next();
  }
}