Chapter 9 — React & Angular Interview Questions (50+ Questions)

This chapter focuses on questions commonly asked for Senior Full Stack Developer (.NET + Angular/React) positions.

Topics:


1. What is React?

Interview Answer

React is a JavaScript library for building user interfaces, especially single-page applications (SPAs).

It was created by Meta (Facebook) and is based on:


Traditional Web Application

Browser

   |

Request HTML

   |

Server Generates Page

   |

New Page Loaded


React Application

Browser

   |

Load Application Once

   |

React Updates Components

   |

DOM Changes


React Features

Component-Based Architecture

UI is divided into reusable components.

Example:

Application

 |

 +-- Header

 |

 +-- Navigation

 |

 +-- ProductList

 |

 +-- Footer


Virtual DOM

React keeps an in-memory representation of the UI.

When state changes:

State Changed

      |

Virtual DOM Comparison

      |

Update Only Changed Elements


Declarative Programming

Instead of:

document.getElementById("title")

.innerHTML="Hello";

React:

<h1>{title}</h1>

You describe what the UI should look like.


Senior Answer

React is a component-based UI library that uses a virtual DOM and declarative programming model to build scalable and maintainable front-end applications.


2. What is a React component?

Interview Answer

A React component is a reusable piece of UI that encapsulates:


Example:

function Welcome() {

    return (

        <h1>Hello World</h1>

    );

}


Using component:

function App(){

    return (

        <Welcome />

    );

}


Component Types

Functional Components

Modern React approach.

Example:

function User(){

 return (

   <div>

      John

   </div>

 );

}


Class Components

Older approach.

Example:

class User extends React.Component {

 render(){

    return <div>John</div>;

 }

}


Component Responsibilities

A good component:

Avoid:


Senior Answer

React components are reusable UI building blocks. I prefer small functional components with hooks and keep business logic separated from presentation.


3. What is JSX?

Interview Answer

JSX is a syntax extension that allows writing HTML-like code inside JavaScript.

Example:

const element = (

    <h1>

       Hello React

    </h1>

);


React converts JSX into JavaScript:

React.createElement(

    "h1",

    null,

    "Hello React"

);


JSX Rules

One Parent Element

Correct:

return (

 <div>

   <h1>Hello</h1>

   <p>Text</p>

 </div>

);

Wrong:

return (

 <h1>Hello</h1>

 <p>Text</p>

);


JavaScript Expressions

Use:

{}

Example:

<h1>

 {user.name}

</h1>


className Instead of class

<div className="container">

</div>


Senior Answer

JSX allows developers to describe UI structure using a syntax similar to HTML while keeping the power of JavaScript expressions.


4. What is the difference between props and state?

Interview Answer

Both props and state store data, but they have different purposes.


Props

Data passed from parent component to child.

Example:

function User(props){

 return (

   <h1>

    {props.name}

   </h1>

 );

}

Parent:

<User name="Victor" />


Props are:


State

Data managed inside a component.

Example:

function Counter(){

 const [count,setCount]

       = useState(0);

 return (

   <button

    onClick={() =>

      setCount(count+1)

    }>

    {count}

   </button>

 );

}


State:


Comparison:

Props

State

Passed from parent

Owned by component

Read-only

Mutable

External data

Internal data

Component communication

Component memory


Senior Answer

Props are used for passing data between components, while state represents internal component data that changes during the component lifecycle.


5. What is the React component lifecycle?

Interview Answer

The lifecycle describes the stages a component goes through:

  1. Mounting
  2. Updating
  3. Unmounting

Mounting

Component appears on screen.

Example:

Create Component

      |

Render

      |

Display


Updating

Occurs when:

Example:

State Update

      |

Re-render


Unmounting

Component removed.

Example:

Navigate Away

      |

Component Destroyed


Functional Components

Hooks replace lifecycle methods.

Old class:

componentDidMount()

Modern:

useEffect(() => {

}, []);


Senior Answer

In modern React, component lifecycle behavior is handled primarily through hooks such as useEffect, which replaces traditional class lifecycle methods.


6. What is the Virtual DOM?

Interview Answer

The Virtual DOM is an in-memory representation of the real DOM used by React to optimize UI updates.


Without Virtual DOM:

State Change

 |

Update Entire DOM

 |

Slow


With Virtual DOM:

State Change

 |

Create New Virtual DOM

 |

Compare With Previous

 |

Update Only Differences


This comparison process is called:

Reconciliation


Example:

Before:

<ul>

<li>Apple</li>

<li>Orange</li>

</ul>

After:

<ul>

<li>Apple</li>

<li>Banana</li>

</ul>

React updates only:

Orange → Banana


Senior Answer

The Virtual DOM improves performance by calculating the minimal set of real DOM changes required after state updates.


7. What is useState in React?

Interview Answer

useState is a React hook used to add state management to functional components.


Example:

import {useState} from "react";

function Counter(){

 const [count,setCount]

       = useState(0);

 return (

 <button

 onClick={() =>

    setCount(count+1)

 }>

 {count}

 </button>

 );

}


Explanation:

const [count,setCount]

means:

Current value:

count

Update function:

setCount

Initial value:

0


Important Rule

Never modify state directly.

Wrong:

count = count + 1;

Correct:

setCount(count + 1);


Senior Answer

useState allows functional components to maintain local state. State updates should always use the setter function to ensure React can correctly trigger rendering.


8. What is useEffect?

Interview Answer

useEffect is a React hook used for performing side effects.

Examples:


Example:

useEffect(() => {

 fetch("/api/users")

 .then(response =>

    response.json()

 )

 .then(data =>

    setUsers(data)

 );

}, []);


The dependency array controls execution.


Empty Array

[]

Runs once after mounting.

Example:

Component Loaded

      |

API Call


Dependency

[userId]

Runs when userId changes.

Example:

userId changed

      |

Load User


No Dependency Array

useEffect(() => {

});

Runs after every render.

Usually avoided.


Senior Answer

useEffect handles side effects in functional components. The dependency array determines when the effect executes and helps prevent unnecessary operations.


9. What is useCallback?

Interview Answer

useCallback memoizes a function so that React does not recreate it on every render.


Example:

Without useCallback:

function Parent(){

 const handleClick = () => {

    console.log("click");

 };

}

Every render creates a new function.


With useCallback:

const handleClick = useCallback(() => {

 console.log("click");

}, []);

React keeps the same function reference.


Why Important?

Useful when passing functions to memoized child components.

Example:

<Child onClick={handleClick}/>


Without:

Parent Render

 |

New Function

 |

Child Re-renders


With:

Parent Render

 |

Same Function Reference

 |

Child Does Not Re-render


Senior Answer

useCallback is used for performance optimization when function identity matters, especially when passing callbacks to memoized child components.


10. What is useMemo?

Interview Answer

useMemo memoizes a calculated value so expensive computations are not repeated unnecessarily.


Example:

const result = useMemo(() => {

 return calculateTotal(items);

}, [items]);


Without:

Every Render

 |

Calculate Total Again


With:

Items Changed?

Yes → Calculate

No → Use Cached Value


Example:

function calculateTotal(products){

 // expensive operation

}


useMemo vs useCallback

useMemo

useCallback

Stores value

Stores function

Returns result

Returns function

Expensive calculations

Function references


Senior Answer

useMemo optimizes expensive calculations by caching results between renders. It should be used carefully because unnecessary memoization can add complexity.

11. What is React Context API?

Interview Answer

React Context API is a built-in mechanism for sharing data between components without passing props manually through every level of the component tree.

It is commonly used for:


Problem: Prop Drilling

Without Context:

id="context1"

App

 |

UserPage

 |

Profile

 |

UserInfo

Passing user:

<UserInfo user={user}/>

through many components becomes difficult.


With Context:

id="context2"

          UserContext

              |

App

              |

        Any Component


Creating Context

const UserContext = createContext();

Provider:

<UserContext.Provider value={user}>

    <Dashboard />

</UserContext.Provider>

Using:

const user = useContext(UserContext);


Advantages


Limitations

Context is not always a replacement for Redux.

Problems:


Senior Answer

Context API is useful for sharing application-wide data such as authentication state or configuration. For complex state management, I usually combine Context with specialized solutions like Redux Toolkit.


12. What is Redux?

Interview Answer

Redux is a predictable state management library used to manage global application state.

It follows a unidirectional data flow pattern.


Architecture:

id="redux1"

Component

   |

Dispatch Action

   |

Reducer

   |

Store

   |

Updated State

   |

Component Re-render


Main Concepts

Store

Central location for application state.

Example:

{

 user:{

   name:"Victor"

 },

 products:[]

}


Action

Describes what happened.

Example:

{

 type:"LOGIN_SUCCESS",

 payload:user

}


Reducer

Function that changes state.

Example:

function reducer(state, action){

 switch(action.type){

 case "LOGIN_SUCCESS":

 return {

    ...state,

    user:action.payload

 };

 }

}


Redux Principles

Single Source of Truth

One global store.


State Is Read-Only

Changes happen through actions.


Pure Reducers

Reducers should not:


Senior Answer

Redux provides centralized state management with predictable state changes through actions and reducers. It is useful for large applications where many components share complex state.


13. What is Redux Toolkit?

Interview Answer

Redux Toolkit is the official modern way to write Redux applications.

It simplifies Redux by reducing boilerplate code.


Traditional Redux:

id="reduxold"

Action file

Reducer file

Constants file

Store setup

Many files.


Redux Toolkit:

id="reduxnew"

Create Slice

Actions + Reducers


Example:

import {

 createSlice

} from "@reduxjs/toolkit";

const counterSlice =

createSlice({

name:"counter",

initialState:{

 value:0

},

reducers:{

 increment:

(state)=>{

    state.value++;

}

}

});


Benefits:


Senior Answer

Redux Toolkit is the recommended approach for Redux development because it simplifies configuration, reduces boilerplate, and provides safer state updates.


14. What is React Router?

Interview Answer

React Router is a library that enables client-side routing in React applications.

It allows navigation between pages without full browser reloads.


Example:

id="router1"

Browser

 |

React Application

 |

Route Matching

 |

Component


Example:

<Route

 path="/users"

 element={<Users/>}

/>


Navigation:

<Link to="/users">

 Users

</Link>


Routes Example

<Routes>

<Route

 path="/"

 element={<Home/>}

/>

<Route

 path="/products"

 element={<Products/>}

/>

</Routes>


Benefits


Protected Route Example

id="router2"

User

 |

Authenticated?

 |

Yes → Page

No → Login


Senior Answer

React Router provides client-side navigation for single-page applications, allowing users to move between views without requesting new HTML pages from the server.


15. What are controlled components in React?

Interview Answer

A controlled component is a form element whose value is controlled by React state.


Example:

function Login(){

const [email,setEmail]

=

useState("");

return (

<input

value={email}

onChange={

e=>setEmail(e.target.value)

}

/>

);

}


Flow:

id="controlled1"

User Types

 |

onChange Event

 |

Update State

 |

React Updates Input


Advantages


Uncontrolled Component

Uses DOM directly.

Example:

const input =

useRef();


Comparison:

Controlled

Uncontrolled

React manages value

DOM manages value

More control

Less code

Easier validation

Uses refs


Senior Answer

I prefer controlled components for enterprise applications because they provide predictable state management and easier validation.


16. How do you optimize React application performance?

Interview Answer

React performance optimization focuses on reducing unnecessary rendering and expensive operations.


Techniques:


1. React.memo

Prevents unnecessary component rendering.

Example:

export default

React.memo(UserCard);


2. useMemo

Cache expensive calculations.

Example:

const total =

useMemo(

()=>calculateTotal(items),

[items]

);


3. useCallback

Maintain stable function references.

Example:

const onClick =

useCallback(()=>{

},[]);


4. Code Splitting

Load only required code.

Example:

const Admin =

lazy(()=>import("./Admin"));


5. Virtualization

For large lists.

Examples:


6. Avoid State Too High

Bad:

id="statebad"

App

 |

Huge State

 |

All Components Re-render

Better:

id="stategood"

Local State

 |

Only Needed Component Updates


Senior Answer

I optimize React applications by reducing unnecessary renders, memoizing expensive operations, lazy loading features, and designing components with appropriate state boundaries.


17. What is Angular?

Interview Answer

Angular is a TypeScript-based front-end framework created by Google for building enterprise web applications.

It provides a complete framework including:


Architecture:

id="angular1"

Angular Application

        |

 Components

        |

 Services

        |

 Modules

        |

Backend API


Angular Features

TypeScript

Provides:


Dependency Injection

Example:

constructor(

 private userService:UserService

){}


RxJS

Handles asynchronous operations.

Example:

users$


Routing

Single-page navigation.


Senior Answer

Angular is a complete enterprise front-end framework that provides a structured architecture with TypeScript, dependency injection, routing, and reactive programming.


18. Explain Angular architecture.

Interview Answer

Angular applications are built from several core building blocks:


Architecture:

id="angular2"

Module

 |

Components

 |

Templates

 |

Services

 |

HTTP Client

 |

Backend API


Component

Controls UI.

Example:

@Component({

 selector:'app-user'

})

export class UserComponent {

}


Template

HTML view:

<h1>

{{user.name}}

</h1>


Service

Contains business logic.

Example:

@Injectable()

export class UserService{

getUsers(){

return this.http.get(

"/api/users"

);

}

}


Directive

Changes DOM behavior.

Example:

<div *ngIf="visible">


Pipe

Transforms data.

Example:

{{price | currency}}


Senior Answer

Angular provides a structured architecture where components handle presentation, services handle business logic, and dependency injection manages object creation.


19. What is an Angular Component?

Interview Answer

An Angular component controls a section of the user interface.

A component contains:


Example:

@Component({

selector:'app-orders',

templateUrl:'orders.html'

})

export class OrdersComponent{

orders=[];

}


Component lifecycle:

id="angularlife"

Create

 |

Initialize

 |

Render

 |

Update

 |

Destroy


Important lifecycle hooks:

ngOnInit

Initialization.

ngOnInit(){

loadData();

}


ngOnDestroy

Cleanup.

ngOnDestroy(){

subscription.unsubscribe();

}


Senior Answer

Angular components encapsulate UI behavior and presentation. I keep components focused on view logic and move business operations into services.


20. What is Angular Dependency Injection?

Interview Answer

Angular Dependency Injection is a design pattern where Angular creates and provides dependencies instead of components creating them manually.


Without DI:

const service =

new UserService();

Problem:


With DI:

constructor(

private userService:UserService

){

}


Registration:

@Injectable({

providedIn:'root'

})

export class UserService{

}


Benefits:


Angular DI Hierarchy

id="angulardi"

Root Injector

      |

Module Injector

      |

Component Injector


Senior Answer

Angular DI provides dependencies through the framework's injector system, improving maintainability, testability, and separation of concerns.

21. What are Angular Modules?

Interview Answer

Angular Modules (NgModule) are containers that organize related components, directives, pipes, and services into logical groups.

They help structure large applications.


Example:

@NgModule({

 declarations:[

   UserComponent,

   UserListComponent

 ],

 imports:[

   CommonModule

 ],

 providers:[

   UserService

 ]

})

export class UserModule {

}


Module Responsibilities

A module defines:


Types of Modules

Root Module

Main application module.

Usually:

id="angularmodule1"

AppModule

 |

Application Startup

Example:

@NgModule({

 bootstrap:[

   AppComponent

 ]

})

export class AppModule {}


Feature Modules

Organize business areas.

Example:

Application

 |

 +-- CustomerModule

 |

 +-- OrderModule

 |

 +-- ProductModule


Shared Module

Contains reusable elements:


Lazy Loaded Modules

Loaded only when needed.

Example:

id="lazy1"

User opens Admin page

        |

Load Admin Module


Senior Answer

Angular modules provide application organization and scalability by grouping related functionality. In enterprise applications I usually separate features into lazy-loaded modules to improve maintainability and performance.


22. What are Angular Services?

Interview Answer

Angular services are classes that contain reusable business logic and data access operations.

They usually handle:


Example:

@Injectable({

 providedIn:'root'

})

export class ProductService {

constructor(

 private http:HttpClient

){}

getProducts(){

 return this.http.get<Product[]>(

   "/api/products"

 );

}

}


Component:

constructor(

 private service:ProductService

){}

ngOnInit(){

 this.service

 .getProducts()

 .subscribe(data=>{

    this.products=data;

 });

}


Good Architecture

Bad:

Component

 |

Business Logic

 |

Database/API


Better:

Component

 |

Service

 |

HTTP Client

 |

API


Benefits


Senior Answer

I keep components focused on presentation and move business logic, API calls, and shared functionality into injectable services.


23. What is RxJS?

Interview Answer

RxJS (Reactive Extensions for JavaScript) is a library for handling asynchronous data streams using Observables.

Angular uses RxJS extensively for:


Example:

this.http

.get<User[]>('/api/users')

.subscribe(users => {

 this.users = users;

});


Flow:

id="rxjs1"

Observable

     |

Stream of Data

     |

Subscriber


Observable Example

const numbers =

new Observable(observer => {

 observer.next(1);

 observer.next(2);

 observer.next(3);

});

Subscriber:

numbers.subscribe(value=>{

 console.log(value);

});

Output:

1

2

3


Benefits


Senior Answer

RxJS provides a reactive programming model for managing asynchronous operations. Angular uses Observables extensively because they support composition and cancellation.


24. What is the difference between Promise and Observable?

Interview Answer

Both handle asynchronous operations, but they behave differently.


Promise

Represents one future value.

Example:

const result =

fetch('/api/users');

Flow:

Request

 |

One Response

 |

Complete


Observable

Represents a stream of values.

Example:

mouseMove$

Flow:

Value 1

 |

Value 2

 |

Value 3

 |

Continue


Comparison:

Promise

Observable

One value

Multiple values

Eager execution

Lazy execution

Cannot cancel easily

Can unsubscribe

Native JavaScript

RxJS


Example:

HTTP call:

Promise:

Request → Response

Observable:

Request → Response → Updates → Updates


Senior Answer

Promises are suitable for one-time asynchronous operations, while Observables are better for streams of data and provide powerful operators, cancellation, and composition.


25. What is Subject in RxJS?

Interview Answer

A Subject is both:

It allows multiple subscribers to receive emitted values.


Example:

const subject =

new Subject<string>();

subject.subscribe(value=>{

 console.log("A:",value);

});

subject.subscribe(value=>{

 console.log("B:",value);

});

subject.next("Hello");

Output:

A: Hello

B: Hello


Architecture:

id="subject1"

          Subject

        /    |    \

Subscriber Subscriber Subscriber


Common Uses


Example

Component communication:

Component A

      |

Subject

      |

Component B


Senior Answer

Subjects allow multicasting values to multiple subscribers and are useful for component communication and shared event streams.


26. What is BehaviorSubject?

Interview Answer

BehaviorSubject is a special type of Subject that stores the latest emitted value and immediately sends it to new subscribers.


Example:

const user$ =

new BehaviorSubject<User | null>(null);


Initial value:

null

After login:

user$.next(user);

New subscriber receives:

Current User


Comparison:

Subject

BehaviorSubject

No initial value

Requires initial value

New subscriber gets future values

New subscriber gets current value

No stored state

Stores latest value


Example:

id="behavior1"

Login

 |

BehaviorSubject

 |

Component opens later

 |

Receives current user


Senior Answer

I use BehaviorSubject when components need access to the current application state, such as logged-in user information or selected items.


27. What is Angular HttpClient?

Interview Answer

HttpClient is Angular's built-in service for communicating with backend APIs.

It supports:


Example:

constructor(

private http:HttpClient

){}

getUsers(){

return this.http.get<User[]>(

 '/api/users'

);

}


POST Example:

createUser(user:User){

return this.http.post(

 '/api/users',

 user

);

}


Features

Typed Responses

this.http

.get<User[]>('/api/users');


Observable Based

HTTP Request

 |

Observable

 |

subscribe()


Interceptor Support

Example:

Automatically add JWT token.


Senior Answer

Angular HttpClient provides a strongly typed, Observable-based API layer for communication with backend services.


28. What are HTTP Interceptors in Angular?

Interview Answer

HTTP Interceptors are services that intercept HTTP requests and responses globally.

They are commonly used for:


Architecture:

id="interceptor1"

Component

 |

HttpClient

 |

Interceptor

 |

API


Example:

Adding JWT:

intercept(

 request:HttpRequest<any>,

 next:HttpHandler

){

const modified =

request.clone({

 setHeaders:{

 Authorization:

 `Bearer ${token}`

 }

});

return next.handle(modified);

}


Without interceptor:

Every request:

headers:{

 Authorization:token

}


With interceptor:

All Requests

 |

Automatic Token Added


Senior Answer

Interceptors provide centralized processing for HTTP communication. I typically use them for authentication headers, global error handling, and request logging.


29. What are Angular Route Guards?

Interview Answer

Route Guards control whether users can navigate to specific routes.

They are used for:


Example:

Protected page:

id="guard1"

User

 |

Route Guard

 |

Authenticated?

 |

Yes → Dashboard

No → Login


Example:

@Injectable()

export class AuthGuard

implements CanActivate {

canActivate(){

 return this.auth.isLoggedIn();

}

}


Route:

{

 path:'admin',

 component:AdminComponent,

 canActivate:[

   AuthGuard

 ]

}


Types


Senior Answer

Route guards enforce navigation rules on the client side. I use them together with backend authorization because client-side security alone is not sufficient.


30. Explain Angular Change Detection.

Interview Answer

Angular Change Detection is the mechanism Angular uses to detect changes in application state and update the DOM.


Example:

id="changedetection1"

Data Changed

      |

Angular Detects Change

      |

DOM Updated


Default Strategy

Angular checks the component tree after:


OnPush Strategy

Improves performance by checking only when:

Example:

@Component({

changeDetection:

ChangeDetectionStrategy.OnPush

})


Comparison:

Default

OnPush

Checks many components

Checks fewer components

Easier

Faster

More CPU usage

Better performance


Senior Answer

Angular change detection updates the view when application state changes. For large applications I use OnPush strategy, immutable data patterns, and Observables to improve performance.

31. What are Angular Signals?

Interview Answer

Angular Signals are a reactive state management feature introduced in Angular 16+ that allows components to track state changes more efficiently.

Signals provide a simpler alternative to some RxJS use cases.


Traditional Angular State

State Change

     |

Change Detection

     |

Check Components

     |

Update UI


Signals Approach

Signal Value Changed

        |

Only Dependent Components Update

        |

UI Refresh


Example

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

export class CounterComponent {

 count = signal(0);

 increment(){

   this.count.update(

      value => value + 1

   );

 }

}

Template:

<button>

{{count()}}

</button>


Computed Signals

Derived values:

total = computed(() =>

   this.price() * this.quantity()

);


Benefits


Senior Answer

Signals provide fine-grained reactive state management in Angular. They allow Angular to know exactly which parts of the UI depend on changed data, improving performance and simplifying component state handling.


32. What is NgRx?

Interview Answer

NgRx is a state management library for Angular applications based on Redux principles.

It provides predictable global state management.


Architecture:

Component

   |

Action

   |

Reducer

   |

Store

   |

Selector

   |

Component


Main Concepts

Store

Central application state.

Example:

{

 user:{

   name:"Victor"

 },

 orders:[]

}


Actions

Describe events.

Example:

{

 type:"Load Orders"

}


Reducers

Update state.


Selectors

Read state efficiently.

Example:

selectOrders()


Effects

Handle side effects:

Example:

Action

 |

Effect

 |

HTTP Call

 |

New Action


Senior Answer

NgRx provides predictable state management for large Angular applications by separating state changes, side effects, and UI components.


33. What is NGXS?

Interview Answer

NGXS is another Angular state management library inspired by Redux but with a simpler API.

It uses:


Example:

@State<UserStateModel>({

 name:'users',

 defaults:{

   users:[]

 }

})

export class UserState {

}


Dispatch action:

this.store.dispatch(

 new LoadUsers()

);


Comparison:

NgRx

NGXS

More Redux-like

Simpler syntax

More boilerplate

Less code

Enterprise usage

Easier learning curve


Senior Answer

NGXS simplifies Angular state management by reducing Redux boilerplate while still providing centralized and predictable application state.


34. Explain Angular Reactive Forms.

Interview Answer

Reactive Forms are a model-driven approach for building forms in Angular.

The form structure is defined in TypeScript.


Example:

form =

new FormGroup({

 name:

 new FormControl(''),

 email:

 new FormControl('')

});


Template:

<input formControlName="name">

<input formControlName="email">


Advantages


Validation:

name:

new FormControl(

 '',

 Validators.required

)


Form state:

FormControl

 |

 FormGroup

 |

 Form


Senior Answer

I prefer Reactive Forms for enterprise applications because they provide better control, validation, and maintainability for complex forms.


35. What is the difference between Reactive Forms and Template-driven Forms?

Interview Answer

Angular provides two approaches for handling forms.


Template-driven Forms

Logic is mainly inside HTML.

Example:

<input

ngModel

required>


Characteristics:


Reactive Forms

Logic is in TypeScript.

Example:

new FormGroup({

 email:

 new FormControl('')

});


Comparison:

Template Forms

Reactive Forms

HTML-driven

Code-driven

Simple forms

Complex forms

Less code

More control

Harder testing

Easier testing


Senior Answer

For simple forms I can use template-driven forms, but for enterprise applications with complex validation and dynamic fields I prefer Reactive Forms.


36. What are Angular Pipes?

Interview Answer

Pipes transform data before displaying it in templates.


Example:

Without pipe:

{{price}}

Output:

100


Currency pipe:

{{price | currency}}

Output:

£100.00


Built-in Pipes

Examples:

Date

{{date | date}}


Uppercase

{{name | uppercase}}


Async

Handles Observables:

{{users$ | async}}


Custom Pipe

Example:

@Pipe({

 name:'capitalize'

})

export class CapitalizePipe {

transform(value:string){

 return value.toUpperCase();

}

}


Senior Answer

Pipes are used for presentation-level data transformation. I avoid putting business logic into pipes and keep them focused on formatting.


37. What are Angular Directives?

Interview Answer

Directives are classes that add behavior or modify the DOM.

There are three types:


1. Component Directives

A component is actually a directive with a template.

Example:

@Component({

 selector:'app-user'

})


2. Structural Directives

Change DOM structure.

Examples:

ngIf

<div *ngIf="isAdmin">

Admin Panel

</div>


ngFor

<li *ngFor="let user of users">

{{user.name}}

</li>


3. Attribute Directives

Change appearance or behavior.

Example:

<div

[ngClass]="active">

</div>


Senior Answer

Directives extend HTML behavior in Angular. Structural directives modify the DOM structure, while attribute directives modify existing elements.


38. What are Angular decorators?

Interview Answer

Decorators are TypeScript features that add metadata to classes.

Angular uses decorators extensively.


Component Decorator

@Component({

selector:'app-user',

templateUrl:'user.html'

})


Injectable Decorator

@Injectable({

providedIn:'root'

})


Directive Decorator

@Directive({

selector:'[highlight]'

})


Module Decorator

@NgModule({

imports:[]

})


Common Decorators

Decorator

Purpose

@Component

Define component

@Injectable

Define service

@Directive

Define directive

@Pipe

Define pipe

@Input

Receive data

@Output

Send events


Senior Answer

Angular decorators provide metadata that tells Angular how classes should behave and how they participate in the framework lifecycle.


39. Compare React and Angular.

Interview Answer

React and Angular are both popular frontend technologies but have different philosophies.


React

Angular

Library

Framework

JavaScript/TypeScript

TypeScript

Flexible architecture

Opinionated architecture

Virtual DOM

Change Detection

JSX

Templates

Redux/Zustand

NgRx/NGXS

Smaller core

Full framework


React Example

Component:

function User(){

 return <h1>User</h1>;

}


Angular Example

Component:

@Component({

selector:'user',

template:'<h1>User</h1>'

})

export class UserComponent{

}


When to Choose React

Good for:


When to Choose Angular

Good for:


Senior Answer

React provides flexibility and a component-based UI model, while Angular provides a complete enterprise framework with built-in solutions for routing, dependency injection, forms, and HTTP communication.


40. How do you design frontend architecture for a large enterprise application?

Interview Answer

A scalable frontend architecture requires separation of responsibilities, reusable components, and clear state management.


Example:

Frontend Application

        |

+----------------+

Presentation Layer

Components

        |

+----------------+

State Layer

Redux / NgRx / Services

        |

+----------------+

Business Layer

Services

        |

+----------------+

API Layer

HTTP Client

        |

Backend APIs


Principles

Component Reusability

Create shared components:


Feature-Based Structure

Example:

src/

 app/

   users/

   orders/

   reports/

   shared/

   core/


Separate Business Logic

Avoid:

Component

 |

1000 lines of logic

Prefer:

Component

 |

Service

 |

API


State Management

Use:

depending on complexity.


Senior Answer

For enterprise frontend applications I use feature-based architecture, reusable components, centralized state management where needed, and clear separation between presentation, business logic, and API communication.

41. What is TypeScript and why is it used in Angular and React projects?

Interview Answer

TypeScript is a strongly typed superset of JavaScript that compiles into JavaScript.

It adds:


JavaScript:

let user = "Victor";

user = 123;

This is allowed.


TypeScript:

let user: string = "Victor";

user = 123;

Compiler error:

Type 'number' is not assignable to type 'string'


Benefits

1. Detect Errors Earlier

Instead of runtime:

Application crashes

You get:

Compile error


2. Better IDE Support

Provides:


3. Better Large Application Maintenance

Example:

interface User {

 id:number;

 name:string;

 email:string;

}

Developers know exactly what data structure is expected.


Senior Answer

TypeScript improves maintainability of large frontend applications by providing static typing, better tooling, and earlier detection of errors. This is especially valuable for enterprise Angular and React applications.


42. What is the difference between interface and type in TypeScript?

Interview Answer

Both define object structures, but they have different capabilities.


Interface

Used mainly for object contracts.

Example:

interface User {

 id:number;

 name:string;

}


Interfaces can be extended:

interface Employee

extends User {

 department:string;

}


Interfaces support declaration merging:

interface User {

 id:number;

}

interface User {

 email:string;

}

Result:

{

 id:number;

 email:string;

}


Type

Type aliases can represent more complex types.

Example:

type User = {

 id:number;

 name:string;

}


Types can create unions:

type Status =

"Active"

|

"Inactive";


Types can combine:

type Employee =

User & {

 department:string;

}


Comparison:

Interface

Type

Object contracts

Any type

Supports merging

Does not merge

Uses extends

Uses intersections

Common in Angular

Common in React


Senior Answer

I use interfaces when defining object contracts and public APIs. I use types when I need unions, intersections, or more advanced type compositions.


43. What are TypeScript Generics?

Interview Answer

Generics allow writing reusable code that works with different types while preserving type safety.


Without Generics:

function getValue(value:any){

 return value;

}

Problem:

Type information is lost.


With Generic:

function getValue<T>(value:T):T{

 return value;

}

Usage:

let number =

getValue<number>(10);

let text =

getValue<string>("Hello");


Generic Interface

Example:

interface Response<T>{

 data:T;

 success:boolean;

}

Usage:

Response<User>

Response<Product>


Angular Example

HttpClient:

this.http

.get<User[]>('/api/users');

The response type is known.


Senior Answer

Generics allow creating reusable components and services while maintaining strong type checking. They are heavily used in Angular services and TypeScript API models.


44. Explain async/await in JavaScript.

Interview Answer

Async/await is a syntax for writing asynchronous code in a cleaner, synchronous-looking way.

It is built on top of Promises.


Promise style:

fetchUsers()

.then(users => {

 console.log(users);

})

.catch(error=>{

});


Async/await:

async function loadUsers(){

 try {

 const users =

 await fetchUsers();

 console.log(users);

 }

 catch(error){

 }

}


Flow:

Call API

 |

Promise Returned

 |

await pauses execution

 |

Result received

 |

Continue


Important Points

An async function always returns a Promise.

Example:

async function test(){

 return 10;

}

Equivalent:

Promise.resolve(10)


Senior Answer

Async/await improves readability of asynchronous JavaScript code by allowing Promise-based operations to be written in a sequential style while keeping error handling with try/catch.


45. What is the difference between Promise and async/await?

Interview Answer

Async/await is not a replacement for Promises; it is a cleaner syntax built on top of them.


Promise:

apiCall()

.then(result=>{

})

.catch(error=>{

});


Async/await:

try {

const result =

await apiCall();

}

catch(error){

}


Comparison:

Promise

Async/Await

Uses callbacks

Uses synchronous style

More chaining

Easier readability

Good for parallel operations

Good for sequential operations


Example:

Sequential:

await getUser();

await getOrders();


Parallel:

const [

user,

orders

] = await Promise.all([

getUser(),

getOrders()

]);


Senior Answer

I use async/await for readable sequential workflows and Promise utilities like Promise.all when executing independent asynchronous operations in parallel.


46. What are WebSockets and when would you use them?

Interview Answer

WebSockets provide a persistent two-way communication channel between client and server.

Unlike HTTP, the server can push data to the client.


HTTP:

Client

 |

Request

 |

Server

 |

Response


WebSocket:

Client

 <================>

Server

Continuous Connection


Use Cases:


Example:

Stock application:

Market Data

 |

WebSocket Server

 |

Angular/React Client

 |

Live Price Update


Technologies:


ASP.NET Example

services.AddSignalR();


Senior Answer

WebSockets are appropriate when applications require real-time bidirectional communication, such as live trading dashboards, notifications, or collaboration systems.


47. What is CORS?

Interview Answer

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls whether a frontend application can call APIs from another origin.


Example:

Frontend:

https://app.company.com

API:

https://api.company.com

Different origins.

Browser blocks request unless API allows it.


Without CORS:

Browser

 |

Blocked Request

 |

API


With CORS:

Browser

 |

Allowed Request

 |

API


ASP.NET Core Example:

builder.Services

.AddCors(options =>

{

 options.AddPolicy("AllowApp",

 policy =>

 {

   policy.AllowAnyOrigin()

         .AllowAnyMethod()

         .AllowAnyHeader();

 });

});


Security Considerations

Avoid:

AllowAnyOrigin()

for production when possible.

Prefer:

https://mycompany.com


Senior Answer

CORS is enforced by browsers to protect users from unauthorized cross-origin requests. APIs should explicitly allow only trusted frontend origins.


48. What are frontend security best practices?

Interview Answer

Frontend security focuses on protecting users, data, and application communication.


1. Prevent XSS

Cross-Site Scripting happens when attackers inject scripts.

Bad:

element.innerHTML =

userInput;

Better:

textContent =

userInput;


2. Protect Authentication Tokens

Avoid storing sensitive tokens in:

localStorage

when possible.

Prefer:

HttpOnly Secure Cookies


3. Use HTTPS

Protect:


4. Validate Input

Client validation improves UX.

Server validation is mandatory.


5. Prevent CSRF

Use:


Senior Answer

Frontend security requires protection against XSS, CSRF, insecure storage, and unauthorized API access. I always combine frontend controls with backend security because the client cannot be trusted.


49. How do you test React or Angular applications?

Interview Answer

Frontend testing usually includes:


Unit Testing

Tests individual functions/components.

Tools:

React:

Angular:


Example:

it('should calculate total',()=>{

expect(total)

.toBe(100);

});


Component Testing

Tests:

Example:

Click Button

 |

Component Updates

 |

Verify Result


End-to-End Testing

Tests full user scenarios.

Tools:

Example:

Open Website

 |

Login

 |

Create Order

 |

Verify Result


Senior Answer

I use a testing pyramid approach: many unit tests, fewer component tests, and a smaller number of end-to-end tests covering critical business scenarios.


50. Explain frontend application performance optimization.

Interview Answer

Frontend performance optimization focuses on reducing load time and unnecessary processing.


1. Code Splitting

Load features only when needed.

Example:

const Reports =

lazy(()=>import('./Reports'));


2. Lazy Loading

Angular example:

{

path:'admin',

loadChildren:

()=>import('./admin/admin.module')

}


3. Optimize Images

Use:


4. Reduce Bundle Size

Remove:


5. Caching

Use:


6. Optimize Rendering

React:

Angular:


7. Virtual Scrolling

For large lists.

Example:

100,000 rows

        |

Render only visible rows


Senior Answer

I improve frontend performance through lazy loading, optimized bundles, efficient rendering strategies, caching, and minimizing unnecessary network requests.


Chapter 9 — React & Angular Completed ✅

Total:

50 Frontend Interview Questions

Covered:

React

✅ Components
✅ JSX
✅ Props and State
✅ Hooks
✅ Context
✅ Redux
✅ Router
✅ Performance

Angular

✅ Architecture
✅ Modules
✅ Services
✅ RxJS
✅ Signals
✅ NgRx / NGXS
✅ Forms
✅ DI
✅ Routing
✅ Performance

TypeScript

✅ Interfaces
✅ Types
✅ Generics
✅ Async Programming

Web Fundamentals

✅ WebSockets
✅ CORS
✅ Security
✅ Testing
✅ Optimization