Angular Interview Question

Absolutely. Since you've asked for detailed interview answers, it's best to cover one question at a time so each topic is complete and easy to study.

We'll start with Question 1.

Angular Interview Question 1

Explain Angular Architecture.


Answer for Interview

Angular follows a Component-Based Architecture, where the application is divided into multiple reusable components. Each component is responsible for a specific part of the UI and its business logic.

The major building blocks of Angular architecture are:

  1. Modules (NgModule/Standalone Components)
  2. Components
  3. Templates
  4. Metadata (Decorators)
  5. Services
  6. Dependency Injection
  7. Directives
  8. Pipes
  9. Routing
  10. RxJS for asynchronous programming

The flow generally looks like this:

Browser
   │
main.ts
   │
AppModule / bootstrapApplication()
   │
AppComponent
   │
Child Components
   │
Services
   │
HTTP Client
   │
Backend API

Each component contains

  • HTML (View)
  • TypeScript (Business Logic)
  • CSS (Styling)

Angular uses Dependency Injection to share services across components and Change Detection to automatically update the UI whenever data changes.

Because Angular separates responsibilities into different layers, applications become scalable, maintainable, and reusable.


Concept and Explanation

Let's understand every building block.

1. Module

A module groups related functionality.

Example:

User Module
Product Module
Admin Module
Shared Module

Purpose

  • Organize application
  • Lazy loading
  • Feature separation

Example

@NgModule({
 declarations: [
   UserComponent
 ],
 imports: [
   CommonModule
 ]
})
export class UserModule {}

2. Component

A component controls one part of the screen.

Example

Header

Sidebar

Dashboard

Footer

Login

Every component contains

component.ts
component.html
component.css

Example

@Component({
 selector:'app-user',
 templateUrl:'user.component.html'
})

export class UserComponent{

 name="Rahul";

}

3. Template

Template is simply HTML.

Example

<h2>{{name}}</h2>

<button (click)="save()">
Save
</button>

It displays data and handles events.


4. Metadata

Metadata tells Angular how to process a class.

Example

@Component({
 selector:'app-user',
 templateUrl:'./user.component.html'
})

Decorator examples

@Component

@NgModule

@Injectable

@Pipe

@Directive

5. Services

Business logic should not be written inside components.

Instead

Component

↓

Service

↓

API

Example

@Injectable({
 providedIn:'root'
})

export class UserService{

}

6. Dependency Injection

Angular automatically creates service objects.

Instead of

const service=new UserService();

Angular injects it.

Example

constructor(private userService:UserService){

}

Benefits

  • Loose coupling
  • Easy testing
  • Reusable

7. Directives

Directives change HTML behavior.

Examples

*ngIf

*ngFor

ngClass

ngStyle

8. Pipes

Transform displayed data.

Example

Uppercase

Currency

Date

Percent

Example

{{salary | currency}}

9. Routing

Allows navigation between pages.

Login

↓

Dashboard

↓

Employee

↓

Reports

Example

const routes=[
{
path:'employee',
component:EmployeeComponent
}
];

10. RxJS

Used for async programming.

Example

HTTP Request

Timer

Events

Search

Angular HttpClient returns Observable.


Real Project Code Example

Imagine Employee Management System.

Folder Structure

src

app

 employee

    employee.component.ts

    employee.component.html

    employee.service.ts

 app-routing.module.ts

 app.module.ts

Employee Service

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  constructor(private http: HttpClient) {}

  getEmployees() {
    return this.http.get<Employee[]>(
      'https://api.company.com/employees'
    );
  }

}

Employee Component

@Component({
 selector:'app-employee',
 templateUrl:'employee.component.html'
})

export class EmployeeComponent implements OnInit{

 employees:Employee[]=[];

 constructor(private employeeService:EmployeeService){}

 ngOnInit(){

   this.employeeService
       .getEmployees()
       .subscribe(data=>{

        this.employees=data;

       });

 }

}

Employee HTML

<table>

<tr *ngFor="let emp of employees">

<td>{{emp.id}}</td>

<td>{{emp.name}}</td>

<td>{{emp.salary}}</td>

</tr>

</table>

Code Explanation Line by Line

Employee Service

@Injectable({

Marks this class as injectable.


providedIn:'root'

Creates a singleton service for the whole application.


constructor(private http:HttpClient)

Inject HttpClient.


getEmployees()

Method to call API.


return this.http.get<Employee[]>();

Returns Observable of employee array.


Component

implements OnInit

Allows using ngOnInit lifecycle hook.


employees=[]

Stores employee data.


constructor(private employeeService:EmployeeService)

Injects service.


ngOnInit()

Runs after component initialization.


subscribe()

Receives API response.


this.employees=data

Stores response.


HTML

*ngFor

Loops through employee list.


{{emp.name}}

Interpolation to display employee name.


Explanation in Hindi

Angular Architecture का मतलब है कि पूरा Angular Application छोटे-छोटे reusable parts में divide किया जाता है।

मान लीजिए आपने Amazon जैसा Project बनाया।

उसमें

Header

Search

Cart

Product List

Footer

ये सभी अलग-अलग Components होंगे।

Component के अंदर

  • HTML
  • CSS
  • TypeScript

रहते हैं।

अगर Employee Data चाहिए तो Component सीधे API नहीं बुलाता।

Flow कुछ ऐसा होता है:

Component

↓

Service

↓

HttpClient

↓

Backend API

↓

Database

Angular में Service Dependency Injection के माध्यम से Component में आती है।

Routing अलग-अलग Pages के बीच Navigation करती है।

RxJS API के asynchronous response को handle करता है।

Modules application को छोटे Feature Modules में divide करते हैं।

इस Architecture का फायदा है:

  • Reusable Code
  • Clean Code
  • Easy Testing
  • Easy Maintenance
  • Large Scale Applications

Why Interviewer Asked This Question

The interviewer wants to evaluate whether you understand Angular beyond writing components. Specifically, they are checking if you know:

  • Overall Angular application flow.
  • Separation of concerns.
  • Component-based design.
  • Service layer.
  • Dependency Injection.
  • Routing.
  • Data flow.
  • Scalable application architecture.

A strong answer demonstrates that you understand how all Angular pieces work together in a real project, not just their definitions.


Candidate Mistakes

  1. Saying Angular architecture only means Components.
  2. Forgetting Services and Dependency Injection.
  3. Ignoring Routing and Modules.
  4. Not explaining the data flow (Component → Service → API → Component).
  5. Confusing Components with Modules.
  6. Not mentioning RxJS and Observables.
  7. Giving only definitions without a real project example.
  8. Failing to explain why Angular uses a component-based architecture.
  9. Not connecting architecture concepts to scalability and maintainability.
  10. Providing theoretical answers without showing practical code.


Angular Interview Question 2

What are Angular Modules?


Answer for Interview

Angular Modules are used to organize an application into logical blocks of functionality. A module groups together related components, directives, pipes, and services.

In Angular (before standalone components became the default), every application had at least one root module called AppModule. Large applications often contain multiple feature modules such as UserModule, AdminModule, and ProductModule.

The main responsibilities of an Angular Module are:

  • Organize related functionality.
  • Declare components, directives, and pipes.
  • Import required Angular and custom modules.
  • Export components for use in other modules.
  • Configure dependency injection (when needed).
  • Support lazy loading for better performance.

In modern Angular (v15+), Standalone Components are recommended for new applications, reducing the need for NgModules. However, many enterprise projects still use NgModules, so they remain a common interview topic.


Concept and Explanation

What is a Module?

Think of a module as a folder of related features.

Example:

Employee Module
    Employee List
    Employee Details
    Employee Service

Product Module
    Product List
    Product Details
    Product Service

Admin Module
    Dashboard
    Reports
    User Management

Each feature has its own module.

This keeps the project organized.


Root Module

Every traditional Angular application starts with a Root Module.

main.ts
      ↓
AppModule
      ↓
AppComponent

Example

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

Feature Module

Feature modules contain related functionality.

Example

Employee Module

EmployeeComponent

EmployeeListComponent

EmployeeDetailsComponent

EmployeeService

Example

@NgModule({

 declarations:[
   EmployeeComponent,
   EmployeeListComponent,
   EmployeeDetailsComponent
 ],

 imports:[
   CommonModule
 ]

})

export class EmployeeModule{}

Shared Module

Contains reusable components.

Example

Loader

Header

Footer

Sidebar

Pagination

Search Box

Custom Pipes

Example

@NgModule({

 declarations:[
   LoaderComponent,
   HeaderComponent,
   FooterComponent
 ],

 exports:[
   LoaderComponent,
   HeaderComponent,
   FooterComponent
 ]

})

export class SharedModule{}

Core Module

Contains singleton services.

Example

Authentication

Logger

HTTP Interceptor

Configuration

API Services

Example

CoreModule

↓

AuthService

↓

LoggerService

↓

Interceptor

Imports

Imports other modules.

Example

imports:[
 BrowserModule,
 FormsModule,
 ReactiveFormsModule,
 HttpClientModule
]

Declarations

Declare components.

Example

declarations:[

LoginComponent,

RegisterComponent

]

Exports

Makes components available outside the module.

Example

exports:[

HeaderComponent,

FooterComponent

]

Providers

Registers services (older style; now providedIn: 'root' is more common).

providers:[

UserService

]

Bootstrap

Starts the application.

bootstrap:[

AppComponent

]

Real Project Example

Suppose you are building an Employee Management System.

Project Structure

src

app

 app.module.ts

 core

 shared

 employee

 admin

 product

 authentication

Employee Module

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { EmployeeComponent } from './employee.component';
import { EmployeeListComponent } from './employee-list.component';
import { EmployeeDetailsComponent } from './employee-details.component';

@NgModule({

 declarations:[
   EmployeeComponent,
   EmployeeListComponent,
   EmployeeDetailsComponent
 ],

 imports:[
   CommonModule
 ]

})

export class EmployeeModule{}

Shared Module

@NgModule({

 declarations:[

HeaderComponent,

FooterComponent,

LoaderComponent

],

 exports:[

HeaderComponent,

FooterComponent,

LoaderComponent

]

})

export class SharedModule{}

App Module

@NgModule({

 declarations:[
 AppComponent
 ],

 imports:[

 BrowserModule,

 EmployeeModule,

 SharedModule,

 HttpClientModule

 ],

 bootstrap:[
 AppComponent
 ]

})

export class AppModule{}

Folder Structure

EmployeeModule

│

├── employee.component.ts

├── employee-list.component.ts

├── employee-details.component.ts

├── employee.service.ts

├── employee-routing.module.ts

└── employee.module.ts

This keeps all employee-related functionality together.


Code Explanation Line by Line

Employee Module

@NgModule({

Marks the class as an Angular Module.


declarations:[

Registers all components that belong to this module.


EmployeeComponent

Angular knows this component belongs to EmployeeModule.


imports:[
CommonModule
]

Imports Angular directives like *ngIf and *ngFor.


export class EmployeeModule{}

Creates the Employee Module.


Shared Module

exports:[

Allows other modules to use exported components.


LoaderComponent

Now LoaderComponent can be used anywhere SharedModule is imported.


App Module

imports:[
EmployeeModule
]

Imports the employee feature into the application.


bootstrap:[
AppComponent
]

Starts the application from AppComponent.


Explanation in Hindi

Angular Module का मतलब है कि Application को छोटे-छोटे Features में Divide करना।

मान लीजिए आपने एक Banking Application बनाई।

अगर सब कुछ एक ही जगह रखेंगे तो Project बहुत बड़ा और Manage करना मुश्किल हो जाएगा।

इसलिए Project को अलग-अलग Modules में बाँटते हैं।

App

↓

Customer Module

↓

Loan Module

↓

Admin Module

↓

Reports Module

हर Module के अंदर उसी Feature के Components, Services और Routing होती है।

उदाहरण:

Employee Module

↓

Employee List

Employee Details

Employee Service

Employee Routing

इसी तरह:

Product Module

↓

Product List

Product Details

Product Service

इससे Code:

  • Clean रहता है
  • Reusable होता है
  • Easy to Maintain होता है
  • Team में अलग-अलग Developers अलग Modules पर काम कर सकते हैं
  • Lazy Loading की मदद से Performance बेहतर होती है

Modern Angular Note: आजकल Angular में Standalone Components का उपयोग बढ़ रहा है, लेकिन बहुत सारे Enterprise Projects अभी भी NgModules का उपयोग करते हैं। इसलिए इंटरव्यू में दोनों के बारे में जानकारी होना फायदेमंद है।


Interview Tips

Tip 1

पहले Definition दें।

"Angular Modules are used to organize related functionality into logical units."


Tip 2

फिर Real Project बताएँ।

Example:

Employee Module

Product Module

Admin Module

Tip 3

Explain Module Responsibilities

Mention:

  • declarations
  • imports
  • exports
  • providers
  • bootstrap

Tip 4

Mention Lazy Loading

Interviewer likes hearing:

"Feature modules can be lazy loaded, which improves initial application performance."


Tip 5

Mention Standalone Components

You can say:

"In Angular 15+ new projects often use Standalone Components, reducing the need for NgModules, but many enterprise applications still use modules."

This shows you're aware of current Angular practices.


Why Interviewer Asked This Question

The interviewer wants to check whether you understand how Angular applications are structured and scaled.

They are evaluating whether you know:

  • How Angular organizes code.
  • Difference between Root Module and Feature Module.
  • Project structure.
  • Modular architecture.
  • Lazy Loading.
  • Reusability.
  • Team collaboration in large applications.
  • Awareness of Standalone Components in newer Angular versions.

Candidate Mistakes

❌ Mistake 1

Thinking Module means Folder.

A module is not just a folder. It is an Angular construct that groups related functionality.


❌ Mistake 2

Confusing Component and Module.

Component = UI.

Module = Collection of related functionality.


❌ Mistake 3

Not explaining declarations, imports, and exports.

Interviewers almost always expect these.


❌ Mistake 4

Forgetting SharedModule and CoreModule.

These are very common in enterprise applications.


❌ Mistake 5

Ignoring Lazy Loading.

One of the biggest advantages of feature modules is lazy loading.


❌ Mistake 6

Saying every service should go in providers.

Modern Angular commonly uses:

@Injectable({
  providedIn: 'root'
})

instead of registering services in module providers.


❌ Mistake 7

Not mentioning Standalone Components.

In recent Angular versions, saying "NgModules are the only way to structure Angular apps" is outdated. Mentioning standalone APIs shows your knowledge is current.


Quick Interview Summary (30-Second Answer)

"Angular Modules are used to organize an application into logical feature areas. A module groups related components, directives, pipes, and services. The root module starts the application, while feature modules like EmployeeModule or AdminModule improve maintainability and support lazy loading. SharedModule contains reusable UI components, and CoreModule typically contains singleton services. Although modern Angular supports standalone components, NgModules are still widely used in enterprise applications."



Angular Interview Question 3

Components vs Directives (Real Project Examples)


Answer for Interview

A Component is a special type of Directive that has its own HTML template and is used to create UI sections.

A Directive does not create its own UI. Instead, it changes the behavior, appearance, or structure of existing HTML elements.

Simply put:

  • Component = Creates UI
  • Directive = Modifies UI

Every Component is technically a Directive, but every Directive is not a Component.


Real Project Example 1 – Employee Management System

Suppose you're building an Employee Management application.

Project Structure

Employee Module

├── employee-list
├── employee-details
├── employee-profile
├── employee.service.ts
├── directives
│      ├── highlight.directive.ts
│      ├── role.directive.ts
│      └── permission.directive.ts

Components

These create screens.

EmployeeListComponent

EmployeeDetailsComponent

EmployeeProfileComponent

LoginComponent

DashboardComponent

Each has:

HTML

CSS

TypeScript

Example:

Employee List Screen

------------------------------------

Employee List

------------------------------------

ID     Name      Salary

1      Rahul     50000

2      Amit      70000

------------------------------------

This entire screen is built using EmployeeListComponent.


Directives

Now imagine HR employees should be highlighted.

Instead of changing every component, create one directive.

<tr appHighlightEmployee>

<td>{{employee.name}}</td>

</tr>

The directive only changes appearance.

It doesn't create a new screen.


Component Example

employee-list.component.ts

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

@Component({
  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent {

  employees = [
    { id: 1, name: 'Rahul', salary: 50000 },
    { id: 2, name: 'Amit', salary: 70000 }
  ];

}

employee-list.component.html

<h2>Employee List</h2>

<table>

<tr *ngFor="let emp of employees">

<td>{{emp.id}}</td>

<td>{{emp.name}}</td>

<td>{{emp.salary}}</td>

</tr>

</table>

This component creates the UI.


Directive Example

Suppose salary greater than 60000 should appear in green.

highlight.directive.ts

import {
 Directive,
 ElementRef,
 Input,
 OnInit
} from '@angular/core';

@Directive({
 selector:'[appHighlight]'
})

export class HighlightDirective implements OnInit{

 @Input() salary:number=0;

 constructor(private element:ElementRef){}

 ngOnInit(){

   if(this.salary>60000){

     this.element.nativeElement.style.backgroundColor='lightgreen';

   }

 }

}

HTML

<tr
*ngFor="let emp of employees"
appHighlight
[salary]="emp.salary">

<td>{{emp.name}}</td>

<td>{{emp.salary}}</td>

</tr>

Output

Rahul   50000

Amit    70000   ← Green Background

Notice:

The directive didn't create the table.

It only changed its behavior.


Real Project Example 2 – Banking Application

Components

LoginComponent

DashboardComponent

TransactionComponent

TransferMoneyComponent

ProfileComponent

Each page is a Component.


Directives

Disable button if user lacks permission

<button appPermission>

Transfer Money

</button>

PermissionDirective

if(!user.canTransfer){

button.disabled=true;

}

No UI is created.

Only behavior changes.


Real Project Example 3 – E-Commerce Website

Components

Product List

Product Details

Cart

Checkout

Orders

Wishlist

Discount Directive

<div
appDiscountHighlight>

Laptop

</div>

Discount items become

  • Yellow
  • Bold
  • Animated

Again

No HTML is created.


Real Project Example 4 – Hospital Management

Components

Doctor List

Patient List

Appointment

Prescription

Billing

Directive

Critical patient

<tr
appCritical>

If patient status is Critical

Background becomes

Red.


Code Explanation Line by Line

Component

@Component({

Marks the class as a Component.


selector:'app-employee-list'

Custom HTML tag.

<app-employee-list>

</app-employee-list>

templateUrl

Points to HTML.


styleUrls

Points to CSS.


employees=[]

Stores employee data.


Directive

@Directive({

Marks class as Directive.


selector:'[appHighlight]'

Applied like an HTML attribute.

<div appHighlight>

ElementRef

Gets actual DOM element.


@Input()

Receives value from component.


salary>60000

Condition.


style.backgroundColor

Changes UI.


Component vs Directive Comparison

Feature Component Directive
Has HTML Template ✅ Yes ❌ No
Creates UI ✅ Yes ❌ No
Changes Existing HTML Sometimes ✅ Yes
Uses @Component
Uses @Directive
Has CSS ❌ Usually No
Has Selector
Used for Pages
Reusable Behavior Limited ✅ Excellent

Explanation in Hindi

मान लीजिए आपने Amazon जैसी Website बनाई।

Component क्या करेगा?

हर Screen एक Component होगी।

Home

Products

Cart

Orders

Profile

इन सभी की अपनी HTML होगी।

उदाहरण

<h2>Products</h2>

<div>

Laptop

</div>

यह पूरा UI Component बनाएगा।


अब Requirement आई

"Discount वाले Products Yellow दिखाओ।"

अगर हर Component में Code लिखेंगे

तो

  • Product Component
  • Wishlist Component
  • Cart Component
  • Search Component

सब जगह Code लिखना पड़ेगा।

इसलिए Directive बनाते हैं।

<div appDiscount>

Laptop

</div>

बस।

जहाँ भी Directive लगाएंगे

Yellow हो जाएगा।

यही Reusability है।


एक और उदाहरण।

Employee Application

Requirement

Manager की Row Green हो।

<tr appManager>

बस।

बाकी Logic Directive करेगा।


Why Interviewer Asked This Question

The interviewer wants to know if you understand when to create a Component versus when to create a Directive. They're checking whether you can build reusable, maintainable Angular applications instead of duplicating UI logic.

A strong answer should include:

  • Components for pages or reusable UI sections.
  • Directives for reusable behavior or DOM manipulation.
  • Real-world examples like permission handling, highlighting rows, or role-based visibility.

Interview Tips

Say this confidently:

"I use Components when I need to build a UI or screen. I use Directives when I want to reuse behavior across multiple components, such as highlighting elements, showing/hiding controls based on permissions, or applying common styling."

This answer demonstrates practical experience.


Candidate Mistakes

❌ Mistake 1

Saying Components and Directives are the same.

They are related, but Components create UI while Directives modify existing UI.


❌ Mistake 2

Creating a Component for every small UI behavior.

For example, making a HighlightComponent just to color a row is unnecessary. A directive is a better fit.


❌ Mistake 3

Using Directives to create HTML.

Directives should enhance or modify existing elements, not generate complete screens.


❌ Mistake 4

Manipulating the DOM directly everywhere.

If you repeatedly write DOM manipulation logic in multiple components, consider moving it into a reusable custom directive.


30-Second Interview Answer

"A Component is used to create a part of the UI and always has its own template. A Directive is used to modify the behavior or appearance of existing HTML elements without creating a new UI. In one of my projects, pages like Employee List and Dashboard were implemented as Components, while reusable behaviors such as highlighting high-salary employees and hiding buttons based on user permissions were implemented as custom Directives."


Angular Interview Question 4

Lifecycle Hooks in Angular


Answer for Interview

Angular Lifecycle Hooks are special methods that Angular automatically calls at different stages of a component's life—from creation to destruction.

Lifecycle hooks allow us to execute custom logic when:

  • Component is created
  • Input data changes
  • View is initialized
  • Content is projected
  • Change detection runs
  • Component is destroyed

In real projects, lifecycle hooks are used for:

  • Calling APIs
  • Initializing data
  • Accessing child components
  • Subscribing to Observables
  • Cleaning up subscriptions
  • Optimizing performance

Angular Lifecycle Flow

Component Created
       │
constructor()
       │
ngOnChanges()
       │
ngOnInit()
       │
ngDoCheck()
       │
ngAfterContentInit()
       │
ngAfterContentChecked()
       │
ngAfterViewInit()
       │
ngAfterViewChecked()
       │
ngOnDestroy()

All Lifecycle Hooks

Hook Purpose Common Usage
constructor Create object and inject dependencies Inject services
ngOnChanges Runs when @Input values change React to parent data
ngOnInit Runs once after component initialization API calls, initial data
ngDoCheck Custom change detection Rarely used
ngAfterContentInit After projected content loads ng-content
ngAfterContentChecked After projected content checked Validation
ngAfterViewInit After component view loads ViewChild
ngAfterViewChecked After every view check Rarely used
ngOnDestroy Before component is destroyed Cleanup subscriptions

Real Project Example

Project

Employee Management System

Requirements:

  • Load employees from API.
  • Access search input using ViewChild.
  • Subscribe to live notifications.
  • Unsubscribe when leaving the page.

employee.component.ts

import {
 Component,
 OnInit,
 OnDestroy,
 AfterViewInit,
 ViewChild,
 ElementRef
} from '@angular/core';

import { Subscription } from 'rxjs';
import { EmployeeService } from './employee.service';

@Component({
 selector: 'app-employee',
 templateUrl: './employee.component.html'
})

export class EmployeeComponent
implements
OnInit,
AfterViewInit,
OnDestroy {

 employees = [];

 subscription!: Subscription;

 @ViewChild('searchBox')
 searchBox!: ElementRef;

 constructor(
   private employeeService: EmployeeService
 ) {}

 ngOnInit() {

   this.subscription =
     this.employeeService
     .getEmployees()
     .subscribe(data => {

        this.employees = data;

     });

 }

 ngAfterViewInit() {

   this.searchBox.nativeElement.focus();

 }

 ngOnDestroy() {

   this.subscription.unsubscribe();

 }

}

employee.component.html

<input
#searchBox
type="text"
placeholder="Search Employee">

<table>

<tr *ngFor="let emp of employees">

<td>{{emp.name}}</td>

<td>{{emp.salary}}</td>

</tr>

</table>

Code Explanation Line by Line


Import Lifecycle Hooks

import {
OnInit,
OnDestroy,
AfterViewInit
}

These interfaces allow Angular to call lifecycle methods.


ViewChild

@ViewChild('searchBox')

Gets reference to HTML input.

Equivalent HTML

<input #searchBox>

Constructor

constructor(
private employeeService:EmployeeService
)

Inject service.

Do NOT call APIs here.


ngOnInit

ngOnInit(){

Runs once after Angular initializes the component.

Best place for

  • API calls
  • Initial variables
  • Loading dropdowns

Subscribe

this.employeeService
.getEmployees()
.subscribe(...)

Calls backend API.


Store Data

this.employees=data;

Display in UI.


ngAfterViewInit

this.searchBox.nativeElement.focus();

Focus cursor automatically.

Cannot do this inside ngOnInit because the view isn't ready yet.


ngOnDestroy

subscription.unsubscribe();

Prevents memory leaks.


Lifecycle Hook Examples from Real Projects


1. constructor()

Real Project

Dependency Injection

constructor(

private authService:AuthService,

private router:Router

){}

Use only for:

  • Injecting services
  • Simple initialization

Don't:

constructor(){

this.loadEmployees();

}

2. ngOnInit()

Employee Project

ngOnInit(){

this.loadEmployees();

this.loadDepartments();

}

Most commonly used hook.


3. ngOnChanges()

Parent sends selected employee.

Parent

<app-employee-details
[selectedEmployee]="employee">
</app-employee-details>

Child

@Input()

selectedEmployee!:Employee;

ngOnChanges(){

console.log(this.selectedEmployee);

}

Runs whenever parent changes data.


4. ngAfterViewInit()

Example

@ViewChild(MatPaginator)

paginator!:MatPaginator;

ngAfterViewInit(){

this.dataSource.paginator=this.paginator;

}

Very common with

  • Material Table
  • Charts
  • Focus
  • DOM

5. ngOnDestroy()

Real Project

this.subscription.unsubscribe();

Also used for

clearInterval()

clearTimeout()

removeEventListener()

Real Project Scenario

Suppose Dashboard Component

Requirement

When Dashboard opens

  • Load Employees
  • Load Notifications
  • Load Charts

When Dashboard closes

  • Stop Notifications
  • Remove Timer
  • Close WebSocket

Lifecycle

Dashboard Opens

↓

constructor

↓

ngOnInit

↓

API Calls

↓

User Works

↓

ngOnDestroy

↓

Cleanup

Explanation in Hindi

Lifecycle Hooks का मतलब है कि Component के जीवन (Life Cycle) के अलग-अलग चरणों में Angular कुछ Methods अपने आप Call करता है।

मान लीजिए आपने Employee Page खोला।

Employee Page Open

↓

Component Create

↓

API Call

↓

Data Show

↓

User Leaves Page

↓

Component Destroy

Angular हर Stage पर अलग Hook चलाता है।


constructor()

Component बनते समय चलता है।

यहाँ केवल Service Inject करनी चाहिए।


ngOnInit()

सबसे ज्यादा इस्तेमाल होने वाला Hook।

यहीं API Call करते हैं।

ngOnInit(){

this.loadEmployees();

}

ngAfterViewInit()

जब पूरा HTML तैयार हो जाए।

Example

input.focus();

ngOnDestroy()

जब User Page छोड़ दे।

unsubscribe()

Memory Leak रोकने के लिए।


Interview Tips

Tip 1

Remember this sentence:

constructor is for Dependency Injection, ngOnInit is for Business Logic.

Interviewers love this answer.


Tip 2

Always mention ngOnDestroy().

Many candidates forget cleanup.

Mention:

  • unsubscribe()
  • clearInterval()
  • remove listeners

Tip 3

Explain one real example.

Example:

"In my employee project, I called the employee API in ngOnInit(), focused the search box in ngAfterViewInit(), and unsubscribed from the employee stream in ngOnDestroy()."

This makes your answer practical.


Tip 4

Know the most commonly used hooks.

In most enterprise projects, you'll mainly use:

  • constructor
  • ngOnInit
  • ngOnChanges
  • ngAfterViewInit
  • ngOnDestroy

The others are used less frequently.


Why Interviewer Asked This Question

The interviewer wants to know if you understand when different stages of a component's lifecycle occur and where to place your logic.

They're checking whether you know:

  • Why APIs belong in ngOnInit().
  • Why ViewChild access belongs in ngAfterViewInit().
  • Why cleanup belongs in ngOnDestroy().
  • How Angular creates and destroys components.

This also helps them assess whether you can avoid common issues like memory leaks.


Candidate Mistakes

❌ Mistake 1

Calling APIs inside the constructor.

Use ngOnInit() instead.


❌ Mistake 2

Using ViewChild in ngOnInit().

The view may not be initialized yet. Use ngAfterViewInit().


❌ Mistake 3

Forgetting to unsubscribe.

This can cause memory leaks, especially with long-lived Observables.


❌ Mistake 4

Thinking all lifecycle hooks are required.

Only implement the hooks you actually need.


❌ Mistake 5

Confusing ngOnChanges() and ngOnInit().

  • ngOnInit() runs once after initialization.
  • ngOnChanges() runs whenever an @Input() value changes.

30-Second Interview Answer

"Angular Lifecycle Hooks are methods that Angular calls automatically during a component's lifecycle. I typically use the constructor for dependency injection, ngOnInit() for API calls and initial data loading, ngAfterViewInit() when I need access to the rendered view (such as ViewChild), and ngOnDestroy() to clean up subscriptions and prevent memory leaks. In my Employee Management project, I loaded employee data in ngOnInit(), focused the search box in ngAfterViewInit(), and unsubscribed from Observables in ngOnDestroy()."




Post a Comment

0 Comments