Friday, 17 July 2026

Angular


Section 1: Angular Basics (1–15)

1. What is Angular?

Answer:
Angular is a TypeScript-based, open-source front-end framework developed by Google for building Single Page Applications (SPAs). It follows a component-based architecture and provides features like dependency injection, routing, forms, HTTP communication, and RxJS for reactive programming.


2. What are the features of Angular?

Answer:

  • Component-based architecture

  • Dependency Injection (DI)

  • Two-way Data Binding

  • Routing

  • Lazy Loading

  • Reactive Forms

  • RxJS Observables

  • Directives

  • Pipes

  • Built-in Testing Support

  • TypeScript support

  • Ahead-of-Time (AOT) Compilation


3. What is SPA?

Answer:

SPA (Single Page Application) loads a single HTML page and dynamically updates content without reloading the entire page.

Examples:

  • Gmail

  • Facebook

  • LinkedIn

Advantages:

  • Fast navigation

  • Better user experience

  • Reduced server load


4. Difference between AngularJS and Angular?

AngularJSAngular
JavaScriptTypeScript
MVCComponent-based
ControllersComponents
Poor PerformanceBetter Performance
No Mobile SupportMobile Friendly
No Lazy LoadingSupports Lazy Loading

5. Why Angular uses TypeScript?

Answer:

TypeScript provides:

  • Strong Typing

  • Interfaces

  • Classes

  • Better IntelliSense

  • Easier Debugging

  • Better Code Maintainability


6. What is a Component?

Answer:

A Component controls a specific portion of the UI.

Example:

EmployeeComponent

employee.component.ts

employee.component.html

employee.component.css

7. What is Module?

Answer:

A Module groups related components, directives, services, and pipes.

Example:

AppModule

8. What is AppModule?

Answer:

AppModule is the root module where Angular application starts.


9. What is CLI?

Answer:

Angular CLI is a command-line tool used to create and manage Angular applications.

Examples:

ng new ProjectName

ng serve

ng build

ng test

10. Difference between Component and Module?

ComponentModule
Controls UIGroups Components
HTML + TS + CSSCollection
ReusableRoot Configuration

11. What is Metadata?

Answer:

Metadata tells Angular how to process a class.

Example:

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

12. What is Decorator?

Answer:

Decorators are special functions that add metadata.

Examples:

@Component

@NgModule

@Injectable

@Input

@Output

13. What is Bootstrapping?

Answer:

Bootstrapping is the process of loading the root Angular component during application startup.


14. What is main.ts?

Answer:

It is the application's entry point.

Flow:

main.ts

↓

AppModule

↓

AppComponent

15. Explain Angular Architecture.

Browser

↓

main.ts

↓

AppModule

↓

Components

↓

Services

↓

HttpClient

↓

.NET API

↓

Database

Section 2: Data Binding (16–22)

16. What is Data Binding?

Answer:

Data Binding synchronizes data between the component and the HTML template.


17. Types of Data Binding?

  1. Interpolation

  2. Property Binding

  3. Event Binding

  4. Two-way Binding


18. What is Interpolation?

{{employeeName}}

Displays component data in HTML.


19. Property Binding?

<img [src]="image">

20. Event Binding?

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

21. Two-way Binding?

[(ngModel)]

Example:

<input [(ngModel)]="employee.name">

22. Difference between Property and Event Binding?

PropertyEvent
Component → ViewView → Component

Section 3: Directives (23–30)

23. What is Directive?

A Directive changes the appearance or behavior of DOM elements.


24. Types of Directives?

  • Component

  • Structural

  • Attribute


25. What is *ngIf?

Shows or hides an element.

<div *ngIf="isAdmin">

26. What is *ngFor?

Displays a list.

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

27. What is ngSwitch?

Displays content based on conditions.


28. What is ngClass?

Adds dynamic CSS classes.


29. What is ngStyle?

Applies dynamic styles.


30. Difference between ngIf and hidden?

ngIfhidden
Removes DOMHides Element

Section 4: Components (31–40)

31. Lifecycle Hooks?

  • constructor

  • ngOnChanges

  • ngOnInit

  • ngDoCheck

  • ngAfterContentInit

  • ngAfterViewInit

  • ngOnDestroy


32. Difference between constructor and ngOnInit?

ConstructorngOnInit
Dependency InjectionInitialization
Runs firstRuns after constructor

33. What is ngOnDestroy?

Used to clean up resources and unsubscribe from Observables to prevent memory leaks.


34. Parent to Child Communication?

@Input()

35. Child to Parent Communication?

@Output()

EventEmitter

36. ViewChild?

Access child component or DOM elements.


37. ContentChild?

Access projected content using <ng-content>.


38. Change Detection?

Angular checks the component tree for data changes and updates the view.


39. OnPush Change Detection?

Improves performance by checking changes only when inputs or Observable references change.


40. Standalone Components?

Angular 14+ allows components without NgModule.


Section 5: Services & Dependency Injection (41–50)

41. What is Service?

A Service contains reusable business logic and API communication.


42. Why use Services?

  • Code reuse

  • Separation of concerns

  • API calls

  • Shared state


43. What is Dependency Injection?

DI automatically provides instances of services to components.


44. What is @Injectable?

Marks a class as available for DI.


45. Singleton Service?

A service provided at the root level; only one instance exists across the application.


46. How to inject a Service?

constructor(private employeeService: EmployeeService) {}

47. What is provider?

Registers a service with Angular's injector.


48. Service Scope?

  • Root

  • Module

  • Component


49. Difference between Component and Service?

ComponentService
UI LogicBusiness Logic

50. Why shouldn't API calls be in Components?

To keep components lightweight, reusable, and easier to test.


Section 6: HTTP & RxJS (51–65)

51. How do you call a .NET Web API?

Using Angular HttpClient.

this.http.get<Employee[]>('/api/employees');

52. What is HttpClient?

A built-in Angular service used to make HTTP requests.


53. Difference between GET and POST?

  • GET retrieves data.

  • POST creates new data.


54. Difference between PUT and PATCH?

  • PUT replaces the entire resource.

  • PATCH updates only specified fields.


55. What is an Observable?

An asynchronous data stream provided by RxJS.


56. Difference between Observable and Promise?

ObservablePromise
Multiple valuesSingle value
CancelableNot cancelable
LazyEager

57. What is subscribe()?

Used to receive data emitted by an Observable.


58. What is pipe()?

Allows chaining RxJS operators.


59. Common RxJS operators?

  • map

  • filter

  • tap

  • switchMap

  • mergeMap

  • concatMap

  • debounceTime

  • distinctUntilChanged

  • catchError

  • retry

  • finalize


60. What is Subject?

Acts as both an Observable and an Observer, allowing multicasting.


61. What is BehaviorSubject?

A Subject that stores the latest value and immediately emits it to new subscribers.


62. When would you use BehaviorSubject?

For sharing application state such as logged-in user or theme.


63. What is switchMap?

Switches to a new Observable and cancels the previous one—useful for search boxes.


64. What is debounceTime()?

Delays emissions to reduce frequent API calls during typing.


65. How do you handle HTTP errors?

Use catchError() in the service or an HTTP interceptor for centralized handling.


Section 7: Routing (66–75)

66. What is Routing in Angular?

Answer

Routing enables navigation between different components in a Single Page Application (SPA) without reloading the browser.

For example:

Dashboard
     ↓
Employees
     ↓
Employee Details
     ↓
Employee Edit

Angular uses the @angular/router package to manage routes.

Example:

const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'employees', component: EmployeeComponent },
  { path: 'about', component: AboutComponent }
];

67. How do you configure Routes?

Answer

Routes are configured inside app-routing.module.ts.

const routes: Routes = [
  {
      path:'employees',
      component:EmployeeComponent
  },
  {
      path:'dashboard',
      component:DashboardComponent
  }
];

Import the routing module:

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

68. What is RouterOutlet?

Answer

<router-outlet> is a placeholder where Angular loads the routed component.

Example

<router-outlet></router-outlet>

Without router-outlet, Angular cannot display routed pages.


69. Difference between RouterLink and href?

RouterLinkhref
Angular navigationBrowser navigation
No page reloadFull page reload
FasterSlower
RecommendedAvoid inside Angular

Example

<a routerLink="/employees">Employees</a>

70. What is Lazy Loading?

Answer

Lazy Loading loads feature modules only when the user navigates to them instead of loading the entire application at startup.

Benefits:

  • Faster startup

  • Better performance

  • Smaller bundle size

Example

{
 path:'admin',
 loadChildren:() =>
 import('./admin/admin.module')
 .then(m=>m.AdminModule)
}

71. Advantages of Lazy Loading?

Answer

  • Faster initial loading

  • Reduced JavaScript bundle size

  • Better scalability

  • Lower memory usage

  • Improved user experience


72. What are Route Parameters?

Answer

Route parameters pass dynamic values in the URL.

Example

employees/101
employees/102

Configuration

{
 path:'employee/:id',
 component:EmployeeDetailComponent
}

Access

this.route.snapshot.params['id'];

73. What is ActivatedRoute?

Answer

ActivatedRoute provides access to route information such as:

  • Route parameters

  • Query parameters

  • URL segments

  • Route data

Example

constructor(private route:ActivatedRoute){}

ngOnInit(){
   let id=this.route.snapshot.paramMap.get('id');
}

74. What is Route Resolver?

Answer

A Resolver loads data before navigating to a component.

Flow

Navigation
      ↓
Resolver
      ↓
API
      ↓
Component Opens

Benefits

  • Prevents empty screens

  • Improves user experience

  • Ensures data is available before rendering


75. What are Route Guards?

Answer

Route Guards protect routes by deciding whether navigation is allowed.

Types:

  • CanActivate

  • CanDeactivate

  • Resolve

  • CanLoad

  • CanMatch

Example

canActivate():boolean{

return this.authService.isLoggedIn();

}

Real-world example

Only authenticated users can access the Dashboard.


Section 8: Forms (76–85)

76. What are Template-driven Forms?

Answer

Template-driven forms use Angular directives in the HTML template and rely on ngModel.

Example

<input [(ngModel)]="employee.name">

Best for:

  • Small forms

  • Simple validation


77. What are Reactive Forms?

Answer

Reactive Forms define form controls in the TypeScript class, offering better scalability and testability.

Example

this.employeeForm=this.fb.group({

name:['',Validators.required],

email:['']

});

Advantages

  • Better validation

  • Dynamic forms

  • Unit testing

  • Complex business rules


78. What is FormGroup?

Answer

A FormGroup groups multiple form controls into a single object.

Example

this.form=new FormGroup({

name:new FormControl(),

email:new FormControl()

});

79. What is FormControl?

Answer

A FormControl represents a single input element.

Example

new FormControl('')

80. What is FormBuilder?

Answer

FormBuilder simplifies creating Reactive Forms.

Instead of

new FormGroup()

Use

this.fb.group({

name:[''],

email:['']

});

81. What are Validators?

Answer

Validators validate user input.

Common validators:

  • required

  • email

  • minlength

  • maxlength

  • pattern

Example

Validators.required

82. What is a Custom Validator?

Answer

Custom validators validate business-specific rules.

Example

export function ageValidator(control:AbstractControl){

if(control.value<18)

return {invalidAge:true};

return null;

}

83. What is FormArray?

Answer

FormArray manages a dynamic collection of controls.

Example

Employee

Phone 1

Phone 2

Phone 3

Useful when the number of controls changes dynamically.


84. What are Dynamic Forms?

Answer

Dynamic Forms allow form fields to be generated at runtime based on configuration or API data.

Example

Registration forms where questions change based on user role.


85. How do you Disable or Enable Controls?

Example

this.form.controls['name'].disable();

this.form.controls['name'].enable();

Section 9: Security (86–92)

86. Explain JWT Authentication.

Answer

JWT (JSON Web Token) authenticates users securely.

Flow

Login

↓

.NET API

↓

JWT Token

↓

Angular Stores Token

↓

Interceptor

↓

Authorization Header

↓

API validates JWT

Header

Authorization: Bearer Token

87. What are Route Guards?

Route Guards prevent unauthorized access.

Example

User Logged In?

↓

Yes

↓

Dashboard

↓

No

↓

Login

88. What is an HTTP Interceptor?

Answer

An Interceptor modifies HTTP requests and responses globally.

Uses

  • Attach JWT

  • Logging

  • Error handling

  • Request modification

Example

request.clone({

setHeaders:{

Authorization:'Bearer '+token

}

});

89. What is XSS?

Answer

Cross-Site Scripting (XSS) is an attack where malicious scripts are injected into web pages.

Angular prevents XSS by automatically sanitizing template bindings.

Avoid using innerHTML with untrusted input.


90. What is DomSanitizer?

Answer

DomSanitizer safely displays trusted HTML, URLs, or resources.

Example

this.sanitizer.bypassSecurityTrustHtml(html);

Use it cautiously and only with trusted content.


91. What is CORS?

Answer

CORS (Cross-Origin Resource Sharing) allows a frontend hosted on one domain to access APIs on another domain.

Example

Angular

localhost:4200

.NET API

localhost:5001

Enable CORS in ASP.NET Core.


92. What is CSRF?

Answer

CSRF (Cross-Site Request Forgery) tricks a user's browser into sending unwanted authenticated requests.

Protection methods:

  • Anti-forgery tokens

  • SameSite cookies

  • Token validation

When using JWT in Authorization headers (instead of cookies), CSRF risk is generally much lower.


Section 10: Performance (93–100)

93. How does Lazy Loading improve performance?

Only the required modules are downloaded, reducing the application's initial bundle size and improving startup time.


94. What is trackBy?

trackBy helps Angular identify list items uniquely when using *ngFor, preventing unnecessary DOM updates.

Example

trackById(index:number,item:any){

return item.id;

}

95. What is OnPush Change Detection?

OnPush reduces unnecessary change detection cycles by checking components only when:

  • An @Input() reference changes

  • An event occurs

  • An Observable emits a new value

This improves performance in large applications.


96. Difference between Pure and Impure Pipes?

Pure PipeImpure Pipe
Executes only when input reference changesExecutes on every change detection cycle
Better performanceSlower
Default behaviorUse only when necessary

97. What is Virtual Scrolling?

Virtual Scrolling renders only the visible items instead of the entire list.

Example:

  • 100,000 records

  • Only ~20 visible records are rendered

This significantly improves rendering performance.


98. What is Tree Shaking?

Tree Shaking removes unused JavaScript code during the production build, reducing bundle size.


99. Difference between AOT and JIT?

AOTJIT
Compiles during buildCompiles in the browser
Faster startupSlower startup
Smaller bundleLarger bundle
Used in productionUsed during development

100. How do you optimize Angular applications?

Common techniques:

  • Lazy Loading

  • OnPush Change Detection

  • trackBy with *ngFor

  • Virtual Scrolling

  • Avoid unnecessary subscriptions

  • Unsubscribe in ngOnDestroy

  • Use the async pipe

  • Split feature modules

  • Optimize images and assets

  • Build with production configuration


Advanced Questions (101–115)

101. What are Angular Signals?

Signals, introduced in Angular 16, are a reactive state management primitive that automatically notifies Angular when state changes.

Example:

count = signal(0);

count.set(1);

count.update(v => v + 1);

Advantages:

  • Simpler state management

  • Fine-grained reactivity

  • Reduced change detection overhead


102. Signals vs Observables?

SignalsObservables
State managementAsynchronous streams
Synchronous readsAsync data/events
Simpler syntaxRich RxJS operators
Great for UI stateGreat for HTTP, WebSockets, events

103. What is NgRx?

NgRx is a Redux-inspired state management library for Angular.

Core concepts:

  • Store

  • Actions

  • Reducers

  • Effects

  • Selectors

Best suited for large enterprise applications with complex shared state.


104. What is State Management?

State Management is the process of storing and sharing application data consistently.

Options include:

  • Services + BehaviorSubject

  • Signals

  • NgRx

  • Component Store


105. What is Zone.js?

Zone.js patches asynchronous browser APIs (such as setTimeout, Promises, and DOM events) so Angular knows when asynchronous work completes and can trigger change detection automatically.


106. How does Angular Change Detection work?

Angular traverses the component tree and checks whether bound data has changed.

Strategies:

  • Default

  • OnPush

For better performance, use immutable data with OnPush.


107. Explain Dependency Injection hierarchy.

Angular resolves dependencies through a hierarchy of injectors.

Common scopes:

  • Root injector (application-wide singleton)

  • Feature module injector

  • Component injector

Angular searches from the nearest injector upward until it finds the requested service.


108. What are Standalone APIs?

Standalone APIs allow Angular applications to work without NgModule.

Example:

@Component({
  standalone: true,
  imports: [CommonModule]
})
export class EmployeeComponent {}

Benefits:

  • Less boilerplate

  • Easier lazy loading

  • Simpler application structure


109. What is Angular Universal?

Angular Universal enables Server-Side Rendering (SSR).

Benefits:

  • Faster first page load

  • Better SEO

  • Improved performance on slow devices


110. How do you optimize Angular performance in enterprise applications?

  • Lazy-load feature modules

  • Use OnPush

  • Implement trackBy

  • Use virtual scrolling

  • Cache API responses

  • Minimize unnecessary subscriptions

  • Use production builds (AOT)

  • Optimize images and assets

  • Split large components

  • Use Signals or efficient state management


111. What is a Microfrontend architecture?

Microfrontends split a large frontend into independently developed and deployed applications.

Benefits:

  • Independent deployments

  • Team autonomy

  • Easier scaling

  • Technology flexibility (where appropriate)


112. How do you implement Role-Based Authorization?

  1. User logs in.

  2. Backend returns a JWT containing roles/claims.

  3. Angular stores the token.

  4. Route Guards verify roles before navigation.

  5. Backend also validates the role for every protected API.

Never rely only on frontend checks; always enforce authorization on the server.


113. How do you securely store JWT tokens?

Recommended practices:

  • Prefer secure, HttpOnly cookies for high-security applications when architecture permits.

  • If using browser storage, understand the XSS risks and keep token lifetimes short.

  • Always use HTTPS.

  • Implement refresh tokens and token expiration.

  • Never hardcode secrets in the Angular application.


114. How do you integrate Angular with an ASP.NET Core Web API?

Flow:

Angular Component
        ↓
Angular Service (HttpClient)
        ↓
ASP.NET Core Web API
        ↓
Business Layer
        ↓
Entity Framework Core
        ↓
SQL Server

Use JWT authentication, centralized HTTP interceptors, proper error handling, and RESTful APIs.


115. Explain an end-to-end Login Flow using Angular, JWT, and ASP.NET Core.

Step 1: User enters credentials in Angular.

Step 2: Angular sends a POST request to the ASP.NET Core login API.

Step 3: The backend validates the credentials and generates a JWT containing user claims.

Step 4: Angular stores the token securely (based on your application's security approach).

Step 5: An HTTP Interceptor automatically adds the Authorization: Bearer <token> header to subsequent API requests.

Step 6: ASP.NET Core middleware validates the JWT before executing protected endpoints.

Step 7: Route Guards prevent unauthorized users from accessing protected pages.

Step 8: On token expiration, the application either redirects the user to log in again or uses a refresh-token mechanism if implemented.



No comments:

Post a Comment