Angular Interview Questions
35 questions with detailed answers
Question:
What is Angular and what are its key features?
Answer:
Angular is a TypeScript-based open-source web application framework developed by Google. Key features include: Component-based architecture, Two-way data binding, Dependency injection, Directives and pipes, Routing and navigation, RxJS for reactive programming, CLI for development workflow, Cross-platform development support.
Question:
What are the main differences between Angular and AngularJS?
Answer:
Key differences: Language (Angular uses TypeScript, AngularJS uses JavaScript), Architecture (Angular is component-based, AngularJS is MVC-based), Mobile Support (Angular has better mobile support), Performance (Angular is faster with better change detection), CLI (Angular has powerful CLI tools).
Question:
What are Angular components and how do you create them?
Answer:
Components are the basic building blocks of Angular applications. They control a patch of screen called a view. Create using: @Component({ selector: "app-hello", template: "
{{title}}
" }) export class HelloComponent { title = "Hello World"; }. CLI: ng generate component component-nameQuestion:
Explain the different types of data binding in Angular.
Answer:
Angular supports four types: 1. Interpolation {{value}} - One-way from component to view, 2. Property Binding [property]="value" - One-way from component to view, 3. Event Binding (event)="handler()" - One-way from view to component, 4. Two-way Binding [(ngModel)]="property" - Bidirectional
Question:
What are Angular directives and their types?
Answer:
Directives are classes that add additional behavior to elements. Types: 1. Component Directives (Components with templates), 2. Structural Directives (*ngIf, *ngFor, *ngSwitch), 3. Attribute Directives (ngClass, ngStyle)
Question:
What is Angular CLI and its common commands?
Answer:
Angular CLI is a command-line interface tool. Commands: ng new (create project), ng serve (dev server), ng generate component (create component), ng build (production build), ng test (run tests), ng e2e (end-to-end tests)
Question:
What are Angular services and dependency injection?
Answer:
Services are singleton objects providing functionality across the application. DI is a design pattern where dependencies are provided to a class. Example: @Injectable({ providedIn: "root" }) export class DataService { getData() { return this.http.get("/api/data"); } }
Question:
Explain Angular component lifecycle hooks.
Answer:
Lifecycle hooks: ngOnInit (Initialize after constructor), ngOnChanges (Input changes), ngDoCheck (Custom change detection), ngAfterContentInit (After content projection), ngAfterViewInit (After view init), ngOnDestroy (Cleanup)
Question:
How does routing work in Angular?
Answer:
Angular Router enables navigation between views. Setup: const routes: Routes = [{ path: "home", component: HomeComponent }]; @NgModule({ imports: [RouterModule.forRoot(routes)] }). Template:
Question:
What are Angular pipes and how do you create custom pipes?
Answer:
Pipes transform displayed values without changing original data. Built-in: date, currency, uppercase. Custom: @Pipe({name: "exponential"}) export class ExponentialPipe implements PipeTransform { transform(value: number, exponent = 1): number { return Math.pow(value, exponent); } }
Question:
Explain template-driven vs reactive forms in Angular.
Answer:
Template-driven: Form logic in template, uses ngModel, suitable for simple forms. Reactive: Form logic in component, uses FormControl/FormGroup, better for complex validation. Example: this.userForm = this.fb.group({ name: ["", Validators.required] });
Question:
What are Angular modules and their purpose?
Answer:
NgModules organize related components, directives, pipes, and services. Types: Root Module (AppModule), Feature Modules, Shared Modules, Core Modules. Example: @NgModule({ declarations: [AppComponent], imports: [BrowserModule], providers: [DataService] })
Question:
Explain Angular change detection and OnPush strategy.
Answer:
Change detection checks for data changes and updates DOM. Default: Checks all components on every change. OnPush: Only checks when input properties change, events occur, or observables emit. Use @Component({ changeDetection: ChangeDetectionStrategy.OnPush })
Question:
How are RxJS Observables used in Angular?
Answer:
RxJS provides reactive programming with Observables for async data streams. Usage: HTTP requests (this.http.get("/api/data").subscribe()), Form changes (this.form.valueChanges.pipe(debounceTime(300))), Custom observables (const timer$ = interval(1000))
Question:
What are Angular route guards and their types?
Answer:
Route guards control navigation. Types: CanActivate (Can route be activated?), CanDeactivate (Can user leave?), CanLoad (Can module be loaded?), Resolve (Pre-fetch data). Example: @Injectable() export class AuthGuard implements CanActivate { canActivate(): boolean { return this.authService.isAuthenticated(); } }
Question:
Explain content projection in Angular.
Answer:
Content projection allows inserting content from parent into child component template using ng-content. Example: Child template: , Usage:
Projected content
Question:
What is the difference between ViewChild and ContentChild?
Answer:
ViewChild accesses child components/elements in template, ContentChild accesses projected content. ViewChild works with template elements, ContentChild works with ng-content projected elements.
Question:
How do you create and use HTTP interceptors?
Answer:
Implement HttpInterceptor interface to intercept HTTP requests/responses. Example: @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req, next) { const authReq = req.clone({ headers: req.headers.set("Authorization", "Bearer " + token) }); return next.handle(authReq); } }
Question:
What is Angular Universal and Server-Side Rendering?
Answer:
Angular Universal enables server-side rendering for better SEO and initial load performance. Benefits: Faster initial page load, Better SEO, Social media preview support. Setup: ng add @nguniversal/express-engine
Question:
How do you implement custom validators in reactive forms?
Answer:
Create functions returning ValidationErrors or null. Example: function emailValidator(control: AbstractControl): ValidationErrors | null { const email = control.value; if (!email || email.includes("@")) return null; return { invalidEmail: true }; }
Question:
What are Angular Interceptors and how do you implement them?
Answer:
HTTP Interceptors intercept and modify HTTP requests/responses. Implement HttpInterceptor interface: @Injectable() export class AuthInterceptor implements HttpInterceptor { intercept(req: HttpRequest, next: HttpHandler): Observable> { const authReq = req.clone({ setHeaders: { Authorization: "Bearer " + token } }); return next.handle(authReq); } }
Question:
Explain Angular Guards in detail with examples.
Answer:
Guards control navigation: CanActivate (route access), CanDeactivate (leaving route), CanLoad (lazy loading), Resolve (pre-fetch data). Example: @Injectable() export class AuthGuard implements CanActivate { canActivate(): boolean { return this.authService.isLoggedIn(); } }
Question:
What is Zone.js and how does it work with Angular?
Answer:
Zone.js patches asynchronous operations (setTimeout, Promise, events) to trigger Angular change detection automatically. It creates execution contexts that persist across async operations, allowing Angular to know when to update the UI without manual triggering.
Question:
How do you optimize Angular application performance?
Answer:
Performance optimization techniques: Use OnPush change detection, Lazy loading modules, Tree shaking, AOT compilation, TrackBy functions in *ngFor, Async pipe for observables, Preloading strategies, Bundle analysis, Image optimization, Service workers for caching.
Question:
What are Angular Elements and how to create them?
Answer:
Angular Elements convert Angular components into custom elements (Web Components). Steps: 1. Install @angular/elements, 2. Create component, 3. Use createCustomElement(), 4. Register with customElements.define(). Enables using Angular components in non-Angular applications.
Question:
Explain Angular testing strategies and tools.
Answer:
Testing tools: Jasmine (testing framework), Karma (test runner), Protractor/Cypress (e2e), TestBed (Angular testing utilities). Strategies: Unit testing (components, services), Integration testing (component interactions), E2E testing (user workflows). Use spies, mocks, and fixtures for isolation.
Question:
What is Angular Universal and Server-Side Rendering?
Answer:
Angular Universal enables server-side rendering (SSR) for better SEO, faster initial load, and social media previews. Benefits: Improved performance, Better SEO, Social sharing support. Setup: ng add @nguniversal/express-engine, then npm run build:ssr && npm run serve:ssr
Question:
How do you handle state management in large Angular applications?
Answer:
State management approaches: 1. Services with BehaviorSubject for simple state, 2. NgRx for complex applications (Actions, Reducers, Effects, Selectors), 3. Akita as alternative, 4. NGXS for simpler syntax. Choose based on complexity: Services < NgRx < Custom solutions.
Question:
What are Angular Schematics and how to create custom ones?
Answer:
Schematics are code generators for Angular. Create custom: 1. Install @angular-devkit/schematics-cli, 2. Create schematic project, 3. Define templates and rules, 4. Implement transformation logic. Used for generating components, services, or entire project structures with consistent patterns.
Question:
Explain Angular Ivy renderer and its benefits.
Answer:
Ivy is Angular's modern rendering engine (default since v9). Benefits: Smaller bundle sizes, Faster builds, Better tree-shaking, Improved i18n, Dynamic imports, Better debugging. Features: Incremental compilation, Locality principle, Improved change detection performance.
Question:
How do you implement micro-frontends with Angular?
Answer:
Micro-frontend approaches: 1. Module Federation (Webpack 5), 2. Single-SPA framework, 3. Angular Elements, 4. Iframe integration. Benefits: Independent deployment, Technology diversity, Team autonomy. Challenges: Shared dependencies, Communication between apps, Consistent UX.
Question:
What are Angular Standalone Components and their benefits?
Answer:
Standalone Components (v14+) don't require NgModules. Benefits: Simplified architecture, Reduced boilerplate, Better tree-shaking, Easier lazy loading. Usage: @Component({ standalone: true, imports: [CommonModule] }). Can bootstrap directly: bootstrapApplication(AppComponent).
Question:
How do you implement internationalization (i18n) in Angular?
Answer:
Angular i18n steps: 1. Mark text with i18n attribute, 2. Extract messages (ng extract-i18n), 3. Translate XLIFF files, 4. Configure angular.json for locales, 5. Build for each locale (ng build --localize). Supports pluralization, ICU expressions, and date/number formatting.
Question:
What are Angular Signals and how do they work?
Answer:
Signals (v16+) provide reactive primitives for change detection. Types: signal() (writable), computed() (derived), effect() (side effects). Benefits: Fine-grained reactivity, Better performance, Simplified state management. Example: const count = signal(0); const doubled = computed(() => count() * 2);
Question:
How do you implement Progressive Web App features in Angular?
Answer:
PWA implementation: 1. ng add @angular/pwa, 2. Service Worker for caching, 3. Web App Manifest for installability, 4. Push notifications, 5. Background sync. Features: Offline functionality, App-like experience, Push notifications, Automatic updates, Install prompts.