Angular Interview Questions - Fundamentals (1-30)
Master Angular fundamentals for FAANG interviews: Angular basics, architecture, modules, components, and more with practical examples.
Master Angular fundamentals for FAANG interviews: Angular basics, architecture, modules, components, and more with practical examples. This interview-focused guide covers essential angular interview questions - fundamentals (1-30) concepts for technical interviews.
Angular Interview Questions - Fundamentals (1-30)
This section covers core Angular concepts that are critical for any Angular interview at FAANG companies.
Question 1: What is Angular?
Angular is a platform and framework for building single-page client applications using HTML and TypeScript. It's written in TypeScript, developed by Google, and follows a component-based architecture.
Key Features:
- Component-based architecture
- Declarative templates with data binding
- Dependency injection
- RxJS for reactive programming
- Routing and forms
- Testing utilities
- Angular CLI for scaffolding
Question 2: What are the core building blocks of Angular?
- Components: The basic UI building blocks
- Templates: Define the UI for a component
- Directives: Modify the DOM or add behavior
- Services: Reusable business logic
- Modules: Organize code into cohesive blocks
- Dependency Injection: Provide dependencies to components/services
Question 3: What is an Angular Component?
Components are the fundamental building blocks of an Angular application. A component controls a part of the screen (a view).
Component Structure:
import { Component } from '@angular/core';
@Component({
selector: 'app-user', // CSS selector to use this component
templateUrl: './user.component.html', // Path to template file
styleUrls: ['./user.component.css'] // Path to styles file(s)
})
export class UserComponent {
name = 'Alice'; // Component property
greet() { console.log('Hello!'); } // Component method
}
Question 4: What is a Module in Angular?
Angular modules (NgModule) organize related code into cohesive blocks of functionality. Every Angular app has at least one root module (usually AppModule).
Example Module:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent], // Components, directives, pipes here
imports: [BrowserModule], // Other modules to import
providers: [], // Services available app-wide
bootstrap: [AppComponent] // Root component to bootstrap
})
export class AppModule {}
Question 5: What is the difference between Angular and AngularJS?
| Angular (2+) | AngularJS (1.x) |
|---|---|
| Written in TypeScript | Written in JavaScript |
| Component-based architecture | MVC architecture |
| Mobile-first approach | No mobile support out of box |
Uses @Component, @NgModule, etc. | Uses directives, controllers |
| Faster rendering (uses virtual DOM-like change detection) | Slower performance on large apps |
Question 6: What is Data Binding in Angular?
Data binding is a mechanism that connects component data to the view (template). There are four types:
- Interpolation:
{{ expression }} - Property Binding:
[property]="value" - Event Binding:
(event)="handler()" - Two-way Binding:
[(ngModel)]="property"
Example:
<!-- 1. Interpolation -->
<h1>Hello, {{ name }}!</h1>
<!-- 2. Property Binding -->
<img [src]="imageUrl" alt="Profile">
<!-- 3. Event Binding -->
<button (click)="handleClick()">Click me!</button>
<!-- 4. Two-way Binding (needs FormsModule!) -->
<input [(ngModel)]="username">
Question 7: What is Interpolation?
Interpolation allows you to embed component property values into the template using double curly braces {{ }}.
Example:
// Component
export class AppComponent {
title = 'My Angular App';
}
<!-- Template -->
<h1>{{ title }}</h1>
Question 8: What is Property Binding?
Property binding lets you set the value of an HTML element's property from the component.
Example:
export class AppComponent {
isDisabled = true;
imageUrl = 'https://example.com/logo.png';
}
<img [src]="imageUrl">
<button [disabled]="isDisabled">Disabled Button</button>
Question 9: What is Event Binding?
Event binding lets you listen for and respond to DOM events like clicks, mouse moves, etc.
Example:
export class AppComponent {
count = 0;
increment() {
this.count++;
}
}
<p>Count: {{ count }}</p>
<button (click)="increment()">Increment</button>
Question 10: What is Two-Way Binding?
Two-way binding combines property and event binding. It updates the component property when the user changes the input, and vice versa!
Example:
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms'; // Required!
@Component({
selector: 'app-name',
template: `
<input [(ngModel)]="name">
<p>Hello, {{ name }}!</p>
`,
standalone: true,
imports: [FormsModule]
})
export class NameComponent {
name = 'Guest';
}
Question 11: What is a Directive in Angular?
Directives are classes that modify the structure of the DOM or the behavior of elements/components.
Types of Directives:
- Components: Directives with a template (
@Component) - Structural Directives: Change DOM structure (
*ngIf,*ngFor,*ngSwitch) - Attribute Directives: Change element appearance/behavior (
ngStyle,ngClass)
Question 12: What are Structural Directives?
Structural directives modify the DOM structure (add/remove elements). They start with an asterisk (*).
Common Structural Directives:
<!-- *ngIf: Conditionally renders -->
<div *ngIf="isLoggedIn; else loginPrompt">
Welcome back!
</div>
<ng-template #loginPrompt>Please log in.</ng-template>
<!-- *ngFor: Repeats element for each item -->
<ul>
<li *ngFor="let product of products; index as i">
{{ i + 1 }}. {{ product.name }}
</li>
</ul>
<!-- *ngSwitch: Conditional rendering with multiple cases -->
<div [ngSwitch]="color">
<p *ngSwitchCase="'red'">Red</p>
<p *ngSwitchCase="'blue'">Blue</p>
<p *ngSwitchDefault>Other color</p>
</div>
Question 13: What are Attribute Directives?
Attribute directives change an element's appearance, behavior, or properties.
Example:
<!-- ngClass: Add/remove classes -->
<div [ngClass]="{ 'active': isActive, 'disabled': isDisabled }">
Content
</div>
<!-- ngStyle: Set inline styles -->
<div [ngStyle]="{ 'font-size': fontSize + 'px', 'color': textColor }">
Styled text
</div>
Question 14: What is a Pipe in Angular?
Pipes transform input data into a desired output format in templates.
Built-in Pipes:
<!-- DatePipe -->
<p>Today is {{ today | date:'fullDate' }}</p>
<!-- UpperCasePipe, LowerCasePipe -->
<p>{{ 'hello' | uppercase }}</p>
<p>{{ 'WORLD' | lowercase }}</p>
<!-- CurrencyPipe -->
<p>Price: {{ price | currency:'USD':'symbol':'1.2-2' }}</p>
<!-- DecimalPipe -->
<p>Number: {{ num | number:'1.2-2' }}</p>
<!-- Chaining pipes -->
<p>{{ message | uppercase | slice:0:10 }}</p>
Question 15: What is a Custom Pipe?
You can create your own custom pipes! Use @Pipe decorator.
Example:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'reverse',
standalone: true
})
export class ReversePipe implements PipeTransform {
transform(value: string): string {
return value.split('').reverse().join('');
}
}
<!-- Usage -->
<p>{{ 'hello' | reverse }}</p> <!-- 'olleh' -->
Question 16: What is Angular CLI?
Angular CLI (Command Line Interface) is a powerful tool for initializing, developing, scaffolding, and maintaining Angular applications.
Common Commands:
ng new my-app # Create new app
ng serve # Run development server
ng generate component user # Generate component
ng build # Build app for production
ng test # Run tests
Question 17: What is Angular's Change Detection?
Change detection is Angular's mechanism for checking if component data has changed and updating the DOM accordingly.
How it works:
- Angular uses Zone.js to intercept async operations (events, HTTP, timers)
- When async event occurs, Angular checks for changes from root to all child components
- Updates the DOM if changes are detected
Question 18: What are Angular Lifecycle Hooks?
Lifecycle hooks are methods that give you visibility into key moments of a component/directive's life.
Common Hooks:
import { Component, OnInit, OnDestroy, OnChanges, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-lifecycle',
template: ''
})
export class LifecycleComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {
ngOnChanges(changes) {
// Called when input properties change
}
ngOnInit() {
// Called once after component initialization
console.log('Component initialized!');
}
ngAfterViewInit() {
// Called after view and child views are initialized
}
ngOnDestroy() {
// Called before component is destroyed - clean up here!
}
}
Question 19: What is @Input() Decorator?
@Input() is used to pass data from a parent component to a child component.
Example:
// Parent component
@Component({
selector: 'app-parent',
template: `<app-child [message]="parentMessage"></app-child>`,
standalone: true,
imports: [ChildComponent]
})
export class ParentComponent {
parentMessage = 'Hello from Parent!';
}
// Child component
@Component({
selector: 'app-child',
template: `{{ message }}`,
standalone: true
})
export class ChildComponent {
@Input() message!: string; // Receives data from parent
}
Question 20: What is @Output() Decorator?
@Output() is used to send events/data from a child component to a parent component using EventEmitter.
Example:
// Child component
@Component({
selector: 'app-child',
template: `<button (click)="notifyParent()">Click me!</button>`,
standalone: true
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();
notifyParent() {
this.messageEvent.emit('Hello from Child!');
}
}
// Parent component
@Component({
selector: 'app-parent',
template: `
<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>Received: {{ receivedMessage }}</p>
`,
standalone: true,
imports: [ChildComponent]
})
export class ParentComponent {
receivedMessage = '';
receiveMessage(msg: string) {
this.receivedMessage = msg;
}
}
Question 21: What is a Service in Angular?
Services are classes that encapsulate specific business logic or functionality (like data fetching, calculations, logging, etc.) that can be reused across components.
Example Service:
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' }) // Provided app-wide
export class UserService {
getUsers() {
return ['Alice', 'Bob', 'Charlie'];
}
}
Question 22: What is Dependency Injection (DI)?
Dependency Injection is a design pattern in which a class receives its dependencies from external sources rather than creating them itself. Angular's DI system creates and provides dependencies to classes.
Example of DI in Component:
import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-user-list',
template: `
<ul>
<li *ngFor="let user of users">{{ user }}</li>
</ul>
`,
standalone: true,
imports: [CommonModule]
})
export class UserListComponent implements OnInit {
users!: string[];
// UserService is injected via constructor!
constructor(private userService: UserService) {}
ngOnInit() {
this.users = this.userService.getUsers();
}
}
Question 23: What is @Injectable() Decorator?
@Injectable() decorator marks a class as available to the Angular dependency injection system. The providedIn option specifies where the service is provided (e.g., 'root' makes it singleton app-wide).
Question 24: What is a Singleton Service?
A singleton service is a service with only one instance shared across the entire application. When you use providedIn: 'root', the service is a singleton by default!
Question 25: What is NgZone?
NgZone is a service that helps Angular execute asynchronous operations inside an Angular zone, ensuring change detection runs after async tasks complete!
Question 26: What is Angular's @ViewChild Decorator?
@ViewChild() allows you to get a reference to a DOM element or child component in the parent component class!
Example:
import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
@Component({
selector: 'app-view-child',
template: `<input #nameInput type="text">`,
standalone: true
})
export class ViewChildComponent implements AfterViewInit {
@ViewChild('nameInput') nameInput!: ElementRef;
ngAfterViewInit() {
this.nameInput.nativeElement.focus(); // Focus input on init!
}
}
Question 27: What is @ViewChildren?
@ViewChildren (plural) returns a QueryList of all matching child components/directives/elements.
Question 28: What is @ContentChild and @ContentChildren?
@ContentChild: Gets a reference to a projected element/component (fromng-content)@ContentChildren: Gets a list of projected elements/components
Question 29: What is Angular's trackBy in *ngFor?
trackBy is a function that helps Angular track items in an *ngFor loop to optimize DOM updates (prevents re-rendering all items when the list changes)!
Example:
export class ProductListComponent {
products = [
{ id: 1, name: 'Laptop' },
{ id: 2, name: 'Phone' }
];
// Use product.id as unique identifier!
trackByProductId(index: number, product: any): number {
return product.id;
}
}
<ul>
<li *ngFor="let product of products; trackBy: trackByProductId">
{{ product.name }}
</li>
</ul>
Question 30: What are Angular Standalone Components?
Standalone components (introduced in Angular 14) don't require an NgModule! They can directly import other components/directives/pipes using their imports array.
Example:
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ButtonComponent } from './button.component';
@Component({
selector: 'app-standalone',
template: `
<h1>Standalone Component</h1>
<app-button></app-button>
`,
standalone: true, // <-- Mark as standalone
imports: [CommonModule, ButtonComponent] // Import dependencies directly
})
export class StandaloneComponent {}