Angular Home
Simple Explanation
Angular is used to build browser applications that have many screens, forms, buttons, tables, user actions, and backend API communication.
A normal static website mostly shows fixed content. An Angular application can change the screen without reloading the whole page. This is why Angular is often used for dashboards, admin portals, banking portals, learning portals, CRM systems, HR systems, and project management systems.
The easiest way to understand Angular is this: Angular breaks a web application into small reusable pieces called components. Each component has its own data, HTML view, and behavior. Services are used for reusable logic and API calls. Routing is used to move between pages.
Syntax
ng new my-app
cd my-app
ng serveExample
Example
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
standalone: true,
template: `<h1>Hello Angular</h1>`
})
export class AppComponent {}
Output
Try it Yourself
Install Angular CLI.Example Explained
| Word / Code | Meaning |
|---|---|
| Angular | A frontend framework that runs in the browser. |
| TypeScript | The language used to write Angular code. |
| Component | A reusable UI block. |
| Service | A reusable class for logic or API calls. |
| Routing | Changing views based on URL. |
Common Mistakes
- Learning Angular before basic HTML, CSS, JavaScript, and TypeScript.
- Putting the whole application into one component.
- Calling Angular a backend framework.
- Ignoring the browser console when errors happen.
Business Use Case
An institute can build a student portal with login, dashboard, courses, projects, certificates, and admin pages using Angular.
Real-Time Scenario
A student opens an institute portal. Angular loads once in the browser, shows the dashboard, and later changes to projects, certificates, and profile pages without reloading the full website.
Practice Exercises
Do these tasks:
- Install Angular CLI.
- Create a new Angular app.
- Run it locally.
- Change the first heading.
- Write what Angular is in your own words.
Quick Interview Answer
Angular is a frontend framework for building component-based browser applications with TypeScript.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/
- Official Link: https://angular.dev/
Angular Intro
Simple Explanation
Angular is not just one small library. It gives a full structure for frontend development. You can create components, show data in templates, navigate between pages, validate forms, call backend APIs, and organize business logic using services.
Angular is useful when many developers work on the same application because the framework gives common patterns. Everyone follows components, services, routes, and forms instead of creating random structures.
Angular is different from AngularJS. AngularJS is the older version. Modern Angular uses components, TypeScript, standalone APIs, and a different architecture.
Syntax
Component + Template + Service + Router + Form + HTTP = Angular AppExample
Example
@Component({
selector: 'app-message',
standalone: true,
template: `<p>{{ message }}</p>`
})
export class MessageComponent {
message = 'Angular uses components';
}
Output
Try it Yourself
Define Angular in one paragraph.Example Explained
| Word / Code | Meaning |
|---|---|
| @Component | Defines a component. |
| template | HTML shown by the component. |
| message | Component property. |
| {{ message }} | Displays component data in HTML. |
Common Mistakes
- Confusing Angular with AngularJS.
- Thinking Angular is only for small pages.
- Skipping TypeScript.
- Not learning components first.
Business Use Case
A healthcare portal can use Angular for patient details, doctor schedules, appointment forms, billing screens, and reports.
Real-Time Scenario
A company builds an employee self-service portal where employees can view payslips, submit leave requests, update profile details, and see announcements from one Angular application.
Practice Exercises
Do these tasks:
- Define Angular in one paragraph.
- List five Angular features.
- Create a message component.
- Explain Angular vs AngularJS.
Quick Interview Answer
Angular provides a complete structure for building large frontend applications.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_intro.asp
- Official Link: https://angular.dev/overview
Angular Get Started
Simple Explanation
To develop Angular applications, you need Node.js, npm, and Angular CLI. Node.js gives the runtime for development tools. npm installs packages. Angular CLI creates and manages Angular projects.
After installation, you create a project using ng new. Then you enter the project folder and run ng serve. The browser usually opens the app at http://localhost:4200.
When you save changes, the development server rebuilds and reloads the browser automatically.
Syntax
npm install -g @angular/cli
ng new app-name
cd app-name
ng serveExample
Example
npm install -g @angular/cli
ng version
ng new student-app
cd student-app
ng serve --open
Output
Try it Yourself
Install Node.js.Example Explained
| Word / Code | Meaning |
|---|---|
| npm install -g @angular/cli | Installs Angular CLI globally. |
| ng version | Checks Angular CLI version. |
| ng new | Creates a new Angular project. |
| ng serve | Runs the project locally. |
| --open | Opens the browser automatically. |
Common Mistakes
- Running ng serve outside the project folder.
- Forgetting npm install after downloading a project.
- Port 4200 already in use.
- Using an old Node.js version.
Business Use Case
A company can give a new developer a project folder. The developer runs npm install and ng serve to start development quickly.
Real-Time Scenario
A new developer joins a project. They install Node.js and Angular CLI, run npm install, start the project with ng serve, and immediately see the local application for development.
Practice Exercises
Do these tasks:
- Install Node.js.
- Install Angular CLI.
- Create student-app.
- Run ng serve.
- Run on port 4300.
Quick Interview Answer
Angular CLI is the main tool used to create, run, build, and generate Angular code.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_getstarted.asp
- Official Link: https://angular.dev/tools/cli
Angular First App
Simple Explanation
Every Angular application needs a starting point. The browser loads index.html. Angular starts from main.ts. The root component is bootstrapped and shown inside its selector.
If the root component selector is app-root, index.html should contain <app-root></app-root>. Angular finds that tag and renders the component there.
This is important because beginners often think the component directly replaces index.html. Actually, index.html is the host page, and Angular renders inside it.
Syntax
bootstrapApplication(AppComponent)Example
Example
import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
standalone: true,
template: `<h1>My First Angular App</h1>`
})
class AppComponent {}
bootstrapApplication(AppComponent);
Output
Try it Yourself
Open main.ts.Example Explained
| Word / Code | Meaning |
|---|---|
| bootstrapApplication | Starts the Angular application. |
| AppComponent | Root component. |
| selector: app-root | HTML tag where the component appears. |
| index.html | Host page loaded by the browser. |
Common Mistakes
- Deleting the root selector from index.html.
- Changing selector in component but not in index.html.
- Putting all app logic in main.ts.
- Forgetting to check browser console errors.
Business Use Case
A first internal company app can start with a root layout that later contains header, sidebar, dashboard, and routed pages.
Real-Time Scenario
A team creates a proof-of-concept dashboard. The root component first displays a welcome screen, and later the team adds child components for menus, cards, and tables.
Practice Exercises
Do these tasks:
- Open main.ts.
- Find app-root in index.html.
- Change root heading.
- Create a second component.
Quick Interview Answer
Angular starts from main.ts and renders the root component into the host page.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_first_app.asp
- Official Link: https://angular.dev/tutorials
Angular Templates
Simple Explanation
A template controls what the user sees. It can display text, bind values, handle clicks, repeat lists, show conditions, use pipes, and include child components.
A template should be simple and readable. Do not put heavy business logic in HTML. Keep complex logic in the component class or in services.
Templates connect the component class to the browser page. When component data changes, Angular updates the template.
Syntax
template: `<h1>{{ title }}</h1>`
// or
templateUrl: './app.component.html'Example
Example
export class DashboardComponent {
title = 'Student Dashboard';
isLoading = false;
}
// template
// <h1>{{ title }}</h1>
// @if (isLoading) { <p>Loading...</p> }
Output
Try it Yourself
Create a title property.Example Explained
| Word / Code | Meaning |
|---|---|
| template | Inline HTML inside component metadata. |
| templateUrl | Path to external HTML file. |
| {{ title }} | Interpolation. |
| @if | Conditional display. |
Common Mistakes
- Putting too much logic inside templates.
- Using wrong property names.
- Not handling loading or empty states.
- Making one template too large.
Business Use Case
A dashboard template can show summary cards, filters, charts, and tables while the component class controls state.
Real-Time Scenario
A dashboard component receives API data and the template displays cards, tables, messages, buttons, and conditional loading text based on the component state.
Practice Exercises
Do these tasks:
- Create a title property.
- Display it in template.
- Add loading condition.
- Move large template to separate HTML file.
Quick Interview Answer
Angular templates display component data and react to component state.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_templates.asp
- Official Link: https://angular.dev/guide/templates
Interpolation
Simple Explanation
Interpolation is the easiest way to show data from the component class in HTML. It is used for headings, names, counts, labels, messages, and simple output.
When the component property changes, Angular updates the displayed text. This gives a direct connection between TypeScript data and the template.
Interpolation is for text content. For element properties like disabled or src, use property binding.
Syntax
{{ expression }}Example
Example
export class StudentComponent {
studentName = 'Asha';
course = 'Angular';
}
// template
// <h2>{{ studentName }}</h2>
// <p>Course: {{ course }}</p>
Output
Try it Yourself
Display your name.Example Explained
| Word / Code | Meaning |
|---|---|
| {{ }} | Interpolation syntax. |
| expression | A simple value or expression. |
| studentName | Component property. |
| course | Another property displayed in HTML. |
Common Mistakes
- Using a property name that does not exist.
- Putting long calculations inside interpolation.
- Using interpolation for attributes where property binding is better.
- Displaying undefined values without checking.
Business Use Case
A student profile page can use interpolation to show name, email, course, status, and enrollment number.
Real-Time Scenario
A profile page displays the logged-in user's name, email, role, and department using interpolation from the component data.
Practice Exercises
Do these tasks:
- Display your name.
- Display course name.
- Display a calculated fullName.
- Try a wrong property and read the error.
Quick Interview Answer
Interpolation is used to show component values inside the template.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_templates_interpolation.asp
- Official Link: https://angular.dev/guide/templates/binding
Reference Variables
Simple Explanation
A template reference variable is created with #name. It lets the template refer to an input, form, component, or element.
For example, #emailInput can refer to an input field. You can read emailInput.value when a button is clicked.
Use reference variables for simple template access. For complex form handling, use Angular forms.
Syntax
#variableNameExample
Example
<input #emailInput placeholder='Email'>
<button (click)='send(emailInput.value)'>Send</button>
// component
send(email: string) {
console.log(email);
}
Output
Try it Yourself
Create an input with #search.Example Explained
| Word / Code | Meaning |
|---|---|
| #emailInput | Template reference variable. |
| emailInput.value | Reads the input value. |
| (click) | Event binding. |
| send() | Component method called by the button. |
Common Mistakes
- Using template references for very complex forms.
- Trying to access a reference outside its template scope.
- Using unclear names like #x or #a.
- Forgetting that the value may be empty.
Business Use Case
A quick search bar can use a reference variable to pass the typed search text to a method.
Real-Time Scenario
A search page has an input box and a Search button. A template reference variable reads the current input value and sends it to the search method.
Practice Exercises
Do these tasks:
- Create an input with #search.
- Pass search.value to a button click.
- Clear input after submit.
- Compare with ngModel.
Quick Interview Answer
Reference variables provide simple local access inside a template.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_templates_refvars.asp
- Official Link: https://angular.dev/guide/templates/variables
Null-Safe Navigation
Simple Explanation
In real applications, data often arrives later from an API. Before the data arrives, an object may be undefined. If you try to read user.profile.name before user exists, the template can fail.
The ?. operator safely reads a property only if the previous object exists. If the object is null or undefined, Angular does not throw an error.
This is useful while loading API data.
Syntax
object?.propertyExample
Example
export class ProfileComponent {
user?: { profile: { name: string } };
}
// template
// <p>{{ user?.profile?.name }}</p>
Output
Try it Yourself
Create optional user object.Example Explained
| Word / Code | Meaning |
|---|---|
| ?. | Null-safe navigation operator. |
| user? | Optional property in TypeScript. |
| profile?.name | Safely reads nested value. |
| undefined | Value not loaded yet. |
Common Mistakes
- Reading nested data before API response arrives.
- Using too many ?. instead of proper loading UI.
- Not handling empty or error states.
- Assuming API data always exists.
Business Use Case
Customer details pages often receive data asynchronously, so null-safe navigation prevents template crashes during loading.
Real-Time Scenario
A customer details page loads data from an API. Before the response arrives, user?.address?.city prevents the template from crashing.
Practice Exercises
Do these tasks:
- Create optional user object.
- Display user?.name.
- Add loading message.
- Replace safe navigation with @if when better.
Quick Interview Answer
Null-safe navigation helps templates avoid errors while data is loading.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_templates_nullsafe.asp
- Official Link: https://angular.dev/guide/templates/expression-syntax
Structural Directives
Simple Explanation
Structural directives control whether elements are created, repeated, or replaced. Older Angular examples use *ngIf and *ngFor. Modern Angular also supports @if and @for.
The star syntax is shorthand. Angular expands it into an ng-template behind the scenes.
Understanding structural directives helps when reading older Angular projects.
Syntax
*ngIf='condition'
*ngFor='let item of items'Example
Example
<div *ngIf='isLoggedIn'>Welcome</div>
<ul>
<li *ngFor='let student of students'>{{ student.name }}</li>
</ul>
Output
Try it Yourself
Create *ngIf example.Example Explained
| Word / Code | Meaning |
|---|---|
| *ngIf | Conditionally creates or removes content. |
| *ngFor | Repeats content for each item. |
| let student | Local loop variable. |
| ng-template | Internal template representation. |
Common Mistakes
- Forgetting CommonModule in older/standalone contexts.
- Not using trackBy for large lists.
- Using old and new control flow without understanding.
- No empty state for lists.
Business Use Case
Older enterprise Angular applications commonly use *ngIf and *ngFor, so developers must understand them even if new apps use @if and @for.
Real-Time Scenario
An older Angular project uses *ngIf to show login/logout buttons and *ngFor to display employee rows in a table.
Practice Exercises
Do these tasks:
- Create *ngIf example.
- Create *ngFor list.
- Rewrite using @if/@for.
- Add empty state.
Quick Interview Answer
Structural directives control whether template blocks exist in the DOM.
Reference Links
ngTemplateOutlet
Simple Explanation
Sometimes the same template structure must be shown in different places. ngTemplateOutlet allows you to define a template once and render it where needed.
This is useful for reusable table cells, empty states, custom list items, and layout sections.
It is an intermediate feature. Beginners should first understand components and templates.
Syntax
<ng-container *ngTemplateOutlet='templateRef'></ng-container>Example
Example
<ng-template #emptyState>
<p>No records found.</p>
</ng-template>
<ng-container *ngTemplateOutlet='emptyState'></ng-container>
Output
Try it Yourself
Create an emptyState template.Example Explained
| Word / Code | Meaning |
|---|---|
| ng-template | Defines template content that is not rendered immediately. |
| #emptyState | Reference to the template. |
| ngTemplateOutlet | Renders the template. |
| ng-container | Logical container without extra DOM element. |
Common Mistakes
- Using ngTemplateOutlet before understanding normal components.
- Making templates too abstract.
- Forgetting template reference variable.
- Using it when a simple component is clearer.
Business Use Case
A reusable data table can allow the parent page to provide a custom row, empty state, or action template.
Real-Time Scenario
A reusable data table allows different pages to provide their own empty-state template, row template, or action button template.
Practice Exercises
Do these tasks:
- Create an emptyState template.
- Render it with ngTemplateOutlet.
- Create a custom row template.
- Compare with reusable component.
Quick Interview Answer
ngTemplateOutlet is used to render reusable template blocks.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_templates_ngtemplateoutlet.asp
- Official Link: https://angular.dev/api/common/NgTemplateOutlet
Statements and $event
Simple Explanation
When a user clicks, types, submits, or changes a value, Angular can run a statement. A statement usually calls a component method.
The special variable $event contains information about the event. For an input event, it can provide the typed value through event.target.
Keep template statements simple. Put real logic in component methods.
Syntax
(event)='statement'
(input)='onInput($event)'Example
Example
<input (input)='onSearch($event)'>
<button (click)='save()'>Save</button>
onSearch(event: Event) {
const value = (event.target as HTMLInputElement).value;
console.log(value);
}
Output
Try it Yourself
Create input event.Example Explained
| Word / Code | Meaning |
|---|---|
| (input) | Runs when input changes. |
| $event | Event object. |
| event.target | Element that triggered the event. |
| (click) | Button click event. |
| save() | Component method. |
Common Mistakes
- Writing long logic directly inside HTML.
- Forgetting to type-cast event.target.
- Using $event when ngModel or forms would be better.
- Method name mismatch.
Business Use Case
A search field can use input events to filter customer records as the user types.
Real-Time Scenario
A live search field captures the user's typed text using $event and filters products as the user enters characters.
Practice Exercises
Do these tasks:
- Create input event.
- Log $event.
- Extract input value.
- Move logic into component method.
Quick Interview Answer
Template statements handle user events and can pass event data to component methods.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_templates_statements.asp
- Official Link: https://angular.dev/guide/templates/event-listeners
Alias with as
Simple Explanation
Alias syntax helps avoid repeating the same async pipe or expression many times in the template.
For example, if users$ | async gives users, you can store it as users and use it inside the block.
This makes templates cleaner and easier to read.
Syntax
@if (value; as localName) {
use localName
}Example
Example
@if (users$ | async; as users) {
<p>Total users: {{ users.length }}</p>
@for (user of users; track user.id) {
<p>{{ user.name }}</p>
}
}
Output
Try it Yourself
Use async alias.Example Explained
| Word / Code | Meaning |
|---|---|
| as users | Creates local alias. |
| users$ | async | Unwraps Observable value. |
| users.length | Uses alias inside block. |
| @for | Loops over aliased value. |
Common Mistakes
- Repeating async pipe many times.
- Using alias outside its scope.
- Not handling loading state.
- Using unclear alias names.
Business Use Case
API list pages can use alias syntax to unwrap data once and use it for count, table rows, and empty state.
Real-Time Scenario
An API list page unwraps users$ once using async alias and then uses the same users variable for total count, table rows, and empty state.
Practice Exercises
Do these tasks:
- Use async alias.
- Show total count.
- Loop over aliased data.
- Add else/loading block.
Quick Interview Answer
Alias syntax makes templates cleaner by storing a value in a local name.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_templates_ngif_as.asp
- Official Link: https://angular.dev/guide/templates/control-flow
Pipes in Templates
Simple Explanation
Pipes are used for display formatting. They do not usually change the original data. Common examples are date formatting, currency formatting, uppercase, lowercase, percent, and json.
Use pipes when the same display transformation is needed in HTML.
Do not use pipes for backend calls or heavy business calculations.
Syntax
{{ value | pipeName }}Example
Example
export class InvoiceComponent {
amount = 12500;
today = new Date();
}
// template
// <p>{{ amount | currency:'INR' }}</p>
// <p>{{ today | date:'mediumDate' }}</p>
Output
Try it Yourself
Use date pipe.Example Explained
| Word / Code | Meaning |
|---|---|
| | | Pipe operator. |
| currency | Formats money. |
| date | Formats date. |
| uppercase | Formats text. |
| json | Displays object data, useful for debugging. |
Common Mistakes
- Putting API calls inside pipes.
- Using json pipe in final user screens.
- Creating heavy impure pipes.
- Forgetting locale/currency needs.
Business Use Case
A billing dashboard uses currency pipes for amounts and date pipes for invoice dates.
Real-Time Scenario
An invoice page formats invoice date, due date, tax percentage, and total amount before showing them to the finance user.
Practice Exercises
Do these tasks:
- Use date pipe.
- Use currency pipe.
- Use uppercase pipe.
- Create a simple custom status pipe.
Quick Interview Answer
Pipes format values for display in the template.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_templates_pipes.asp
- Official Link: https://angular.dev/guide/templates/pipes
Attribute Binding
Simple Explanation
Most of the time, use property binding. Attribute binding is used when you need to set real HTML attributes such as aria-label, colspan, or data-* attributes.
The syntax uses attr. before the attribute name.
Attribute binding is important for accessibility and table layouts.
Syntax
[attr.attribute-name]='value'Example
Example
<button [attr.aria-label]='labelText'>Save</button>
<td [attr.colspan]='columnCount'>Total</td>
Output
Try it Yourself
Bind aria-label.Example Explained
| Word / Code | Meaning |
|---|---|
| [attr.aria-label] | Sets the aria-label attribute. |
| [attr.colspan] | Sets colspan attribute. |
| labelText | Component value. |
| columnCount | Number value used for table layout. |
Common Mistakes
- Using attribute binding when property binding is enough.
- Forgetting attr. prefix.
- Setting accessibility attributes incorrectly.
- Passing null without understanding attribute removal.
Business Use Case
Accessible business applications use aria attributes to support screen readers and keyboard users.
Real-Time Scenario
An accessible form dynamically sets aria-label and aria-describedby attributes so screen readers can explain each field and error message.
Practice Exercises
Do these tasks:
- Bind aria-label.
- Bind colspan.
- Bind data-test-id.
- Compare property binding and attribute binding.
Quick Interview Answer
Attribute binding is used for HTML attributes that need attr. syntax.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_templates_attr_binding.asp
- Official Link: https://angular.dev/guide/templates/binding
TrackBy
Simple Explanation
When a list changes, Angular needs to know which item is which. Tracking by a unique id helps Angular reuse existing DOM elements instead of recreating everything.
Modern @for uses track. Older *ngFor uses trackBy.
This is important for large lists, tables, dashboards, and frequently updated data.
Syntax
@for (item of items; track item.id) { ... }
*ngFor='let item of items; trackBy: trackById'Example
Example
students = [
{ id: 1, name: 'Asha' },
{ id: 2, name: 'Ravi' }
];
// template
// @for (student of students; track student.id) {
// <p>{{ student.name }}</p>
// }
Output
Try it Yourself
Add track to a list.Example Explained
| Word / Code | Meaning |
|---|---|
| track item.id | Modern tracking syntax. |
| trackBy | Older *ngFor tracking function. |
| id | Unique value for each item. |
| DOM reuse | Angular keeps existing elements when possible. |
Common Mistakes
- No tracking in large lists.
- Tracking by non-unique fields.
- Using array index when items can reorder.
- Using random values for tracking.
Business Use Case
An employee table with hundreds of rows should track by employeeId to improve rendering performance.
Real-Time Scenario
An employee table refreshes every few seconds. Tracking rows by employeeId prevents Angular from recreating every row unnecessarily.
Practice Exercises
Do these tasks:
- Add track to a list.
- Use a unique id.
- Try duplicate ids and understand the problem.
- Compare without tracking.
Quick Interview Answer
TrackBy improves list rendering by giving Angular a stable identity for each item.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_templates_trackby.asp
- Official Link: https://angular.dev/guide/templates/control-flow
Angular Components
Simple Explanation
A component controls one part of the UI. It has a TypeScript class, template, styles, and metadata.
Large pages should be split into components. For example, dashboard page can have header, sidebar, card, chart, filter, and table components.
Reusable components make the application easier to maintain.
Syntax
@Component({
selector: 'app-name',
standalone: true,
template: `...`
})Example
Example
@Component({
selector: 'app-student-card',
standalone: true,
template: `<h3>{{ name }}</h3><p>{{ course }}</p>`
})
export class StudentCardComponent {
name = 'Priya';
course = 'Angular';
}
Output
Try it Yourself
Generate a component.Example Explained
| Word / Code | Meaning |
|---|---|
| @Component | Component decorator. |
| selector | HTML tag name. |
| template | Component view. |
| class | Data and methods. |
| standalone | Can be imported directly. |
Common Mistakes
- One giant component.
- Unclear component names.
- Putting backend/API logic in many components.
- No child components for repeated UI.
Business Use Case
StudentCardComponent can be reused in student list, search results, and dashboard widgets.
Real-Time Scenario
A project catalog page uses ProjectCardComponent for each project, HeaderComponent for the top bar, and FilterComponent for category search.
Practice Exercises
Do these tasks:
- Generate a component.
- Use its selector.
- Split a large page.
- Create a reusable card.
Quick Interview Answer
Components are reusable UI blocks in Angular.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_components.asp
- Official Link: https://angular.dev/guide/components
Angular Data Binding
Simple Explanation
Data binding is how Angular moves information between TypeScript and HTML.
Interpolation shows text. Property binding sends component values to element properties. Event binding sends user actions back to component methods. Two-way binding keeps inputs and properties synchronized.
Data binding is one of the most important Angular skills.
Syntax
{{ value }}
[property]='value'
(event)='method()'
[(ngModel)]='value'Example
Example
<h2>{{ title }}</h2>
<button [disabled]='isSaving' (click)='save()'>Save</button>
<input [(ngModel)]='searchText'>
Output
Try it Yourself
Create interpolation.Example Explained
| Word / Code | Meaning |
|---|---|
| Interpolation | Component to template text. |
| Property binding | Component to element property. |
| Event binding | Template event to component method. |
| Two-way binding | Both directions for form-like input. |
Common Mistakes
- Using the wrong binding type.
- Forgetting FormsModule for ngModel.
- Putting complex logic in template.
- Binding to a missing property.
Business Use Case
A customer search page uses interpolation for titles, property binding for disabled buttons, event binding for clicks, and two-way binding for filters.
Real-Time Scenario
A registration page shows a title with interpolation, disables Submit with property binding, listens to Save click with event binding, and uses ngModel for quick input updates.
Practice Exercises
Do these tasks:
- Create interpolation.
- Add property binding.
- Add click event.
- Add ngModel two-way binding.
Quick Interview Answer
Data binding connects the component class and the template.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_data_binding.asp
- Official Link: https://angular.dev/guide/templates/binding
Angular Directives
Simple Explanation
A directive is a class that changes an element or template behavior. Components are also directives with templates.
Attribute directives change appearance or behavior of an element. Structural directives add or remove DOM content.
Custom directives are useful when behavior is repeated in many places.
Syntax
@Directive({ selector: '[appHighlight]' })Example
Example
@Directive({
selector: '[appHighlight]',
standalone: true
})
export class HighlightDirective {
constructor(private el: ElementRef) {
this.el.nativeElement.style.backgroundColor = 'yellow';
}
}
Output
Try it Yourself
Create highlight directive.Example Explained
| Word / Code | Meaning |
|---|---|
| @Directive | Decorator for directive. |
| selector | How directive is applied. |
| ElementRef | Access to host element. |
| attribute directive | Directive used as an attribute. |
Common Mistakes
- Creating directives for one-time styles.
- Forgetting to import standalone directive.
- Overusing direct DOM manipulation.
- Mixing business logic into visual directives.
Business Use Case
A permission directive can show or hide buttons based on user roles across the application.
Real-Time Scenario
A permission directive disables or hides admin-only buttons across many pages based on the logged-in user's role.
Practice Exercises
Do these tasks:
- Create highlight directive.
- Add color input.
- Use directive on multiple elements.
- Explain component vs directive.
Quick Interview Answer
Directives are used to add reusable behavior to template elements.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_directives.asp
- Official Link: https://angular.dev/guide/directives
Angular Events
Simple Explanation
Applications are interactive. Users click buttons, type text, submit forms, and choose dropdown values.
Event binding uses parentheses. The template listens to an event and calls a component method.
Keep event expressions short. Put logic inside the TypeScript method.
Syntax
(click)='save()'
(input)='onInput($event)'
(submit)='submitForm()'Example
Example
count = 0;
increase() {
this.count++;
}
// template
// <p>{{ count }}</p>
// <button (click)='increase()'>Increase</button>
Output
Try it Yourself
Create click counter.Example Explained
| Word / Code | Meaning |
|---|---|
| (click) | Button click event. |
| (input) | Typing/change event for input. |
| $event | Event object. |
| method() | Component method called by event. |
Common Mistakes
- Writing long code in template event.
- Wrong method name.
- Using href for actions that should be buttons.
- Not handling form submit properly.
Business Use Case
Admin screens use click events for edit, delete, save, cancel, search, refresh, and export actions.
Real-Time Scenario
An admin clicks Approve, Reject, Edit, Delete, or Refresh buttons, and each button triggers a component method using event binding.
Practice Exercises
Do these tasks:
- Create click counter.
- Create input event.
- Pass item id in click event.
- Handle form submit.
Quick Interview Answer
Angular events connect user actions to component methods.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_events.asp
- Official Link: https://angular.dev/guide/templates/event-listeners
Angular Conditional
Simple Explanation
Conditional rendering is used when the UI depends on state. Examples: logged in or not, loading or loaded, error or success, admin or normal user, empty list or data list.
Modern Angular uses @if. Older Angular code may use *ngIf.
Always design all states: loading, success, empty, and error.
Syntax
@if (condition) {
HTML
} @else {
HTML
}Example
Example
@if (isLoading) {
<p>Loading...</p>
} @else if (students.length === 0) {
<p>No students found.</p>
} @else {
<p>Students loaded.</p>
}
Output
Try it Yourself
Create isLoading condition.Example Explained
| Word / Code | Meaning |
|---|---|
| @if | Shows block when condition is true. |
| @else if | Checks another condition. |
| @else | Fallback block. |
| isLoading | Common UI state variable. |
Common Mistakes
- No empty state.
- No error state.
- Reading data before it exists.
- Too much logic inside conditions.
Business Use Case
A project dashboard can show loading spinner while fetching projects and empty state when no projects exist.
Real-Time Scenario
A payment page shows different UI for processing, success, failed payment, and retry states using conditional rendering.
Practice Exercises
Do these tasks:
- Create isLoading condition.
- Create empty state.
- Create error state.
- Create admin-only button.
Quick Interview Answer
Conditional rendering displays UI based on component state.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_conditional.asp
- Official Link: https://angular.dev/guide/templates/control-flow
Angular Lists
Simple Explanation
Most real apps display lists: users, students, products, orders, invoices, tickets, certificates, and projects.
Modern Angular uses @for to loop over arrays. Each item should have a tracking value, normally an id.
List templates should handle empty data and should use child components when rows/cards become complex.
Syntax
@for (item of items; track item.id) {
HTML
}Example
Example
students = [
{ id: 1, name: 'Asha' },
{ id: 2, name: 'Ravi' }
];
// template
// @for (student of students; track student.id) {
// <p>{{ student.name }}</p>
// }
Output
Try it Yourself
Display course names.Example Explained
| Word / Code | Meaning |
|---|---|
| @for | Loop block. |
| item of items | Loop each item in array. |
| track item.id | Track identity. |
| student.name | Displays property of current item. |
Common Mistakes
- No track value.
- No empty state.
- Large HTML repeated instead of child component.
- Using non-unique values for tracking.
Business Use Case
An e-commerce app shows product cards using a list. A support app shows ticket rows using a list.
Real-Time Scenario
A course catalog displays many courses as cards using a loop, and each card has title, duration, fee, and enroll button.
Practice Exercises
Do these tasks:
- Display course names.
- Display object list.
- Add empty message.
- Use child card inside @for.
Quick Interview Answer
Angular lists repeat template content for array items.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_lists.asp
- Official Link: https://angular.dev/guide/templates/control-flow
Angular Forms
Simple Explanation
Forms are used for login, signup, profile, search, checkout, feedback, ticket creation, and admin create/edit pages.
Angular has template-driven forms and reactive forms. Template-driven forms are simpler for small forms. Reactive forms are better for complex business forms.
A professional form should have validation, error messages, disabled submit state, loading state, and backend error handling.
Syntax
Template-driven: FormsModule + ngModel
Reactive: ReactiveFormsModule + FormGroupExample
Example
form = new FormGroup({
email: new FormControl('', [Validators.required, Validators.email]),
password: new FormControl('', [Validators.required])
});
Output
Try it Yourself
Create login form.Example Explained
| Word / Code | Meaning |
|---|---|
| FormControl | Represents one field. |
| FormGroup | Group of form controls. |
| Validator | Rule that checks input. |
| ngModel | Template-driven binding. |
| ngSubmit | Angular form submit event. |
Common Mistakes
- No validation.
- Showing all errors before user touches fields.
- Mixing template-driven and reactive APIs incorrectly.
- No backend error handling.
Business Use Case
A student registration form needs required fields, email validation, dropdowns, submit button, and success/error messages.
Real-Time Scenario
A student registration form collects name, email, phone, course, payment details, and validates required fields before calling the backend.
Practice Exercises
Do these tasks:
- Create login form.
- Add required validation.
- Show error messages.
- Disable submit when invalid.
Quick Interview Answer
Angular forms manage user input and validation.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_forms.asp
- Official Link: https://angular.dev/guide/forms
Angular Router
Simple Explanation
Routing lets users navigate between pages without reloading the full application.
A route connects a path like /dashboard to a component like DashboardComponent. RouterOutlet displays the matched route. routerLink creates navigation links.
Routing is essential for dashboards and portals.
Syntax
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent }
];Example
Example
export const routes: Routes = [
{ path: '', redirectTo: 'dashboard', pathMatch: 'full' },
{ path: 'dashboard', loadComponent: () => import('./dashboard.component').then(m => m.DashboardComponent) },
{ path: '**', loadComponent: () => import('./not-found.component').then(m => m.NotFoundComponent) }
];
Output
Try it Yourself
Create three routes.Example Explained
| Word / Code | Meaning |
|---|---|
| Routes | Array of route definitions. |
| path | URL segment. |
| RouterOutlet | Where route component appears. |
| routerLink | Navigation link directive. |
| wildcard | Fallback route for unknown paths. |
Common Mistakes
- Forgetting RouterOutlet.
- Using href instead of routerLink.
- Putting wildcard route first.
- No not-found page.
Business Use Case
A company portal uses routes for dashboard, employees, reports, settings, profile, and admin pages.
Real-Time Scenario
An enterprise portal has routes for dashboard, employees, reports, settings, profile, and admin so users can navigate by URL.
Practice Exercises
Do these tasks:
- Create three routes.
- Add routerLink menu.
- Add not-found route.
- Read route parameter.
Quick Interview Answer
Angular Router controls page navigation inside the application.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_router.asp
- Official Link: https://angular.dev/guide/routing
Services and DI
Simple Explanation
A component should focus on the screen. A service should handle reusable logic such as API calls, authentication, shared state, logging, or notifications.
Dependency injection means Angular gives the service to the component instead of you manually creating it.
This makes code easier to reuse and test.
Syntax
@Injectable({ providedIn: 'root' })
export class MyService {}
private service = inject(MyService);Example
Example
@Injectable({ providedIn: 'root' })
export class StudentService {
getStudents() {
return [{ id: 1, name: 'Asha' }];
}
}
export class StudentListComponent {
private studentService = inject(StudentService);
students = this.studentService.getStudents();
}
Output
Try it Yourself
Generate a service.Example Explained
| Word / Code | Meaning |
|---|---|
| @Injectable | Marks a class as injectable. |
| providedIn: root | One app-wide instance. |
| inject | Gets dependency from Angular injector. |
| service | Reusable logic class. |
Common Mistakes
- Putting API calls in every component.
- Using new Service() manually.
- Creating one huge service for everything.
- Provider missing errors.
Business Use Case
An HR system may use EmployeeService, PayrollService, AuthService, and NotificationService.
Real-Time Scenario
A CustomerService fetches customer data from the backend and is reused by customer list, customer details, and customer edit components.
Practice Exercises
Do these tasks:
- Generate a service.
- Inject it into a component.
- Move mock data to service.
- Create AuthService with login flag.
Quick Interview Answer
Services and dependency injection separate reusable logic from UI components.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_services.asp
- Official Link: https://angular.dev/guide/di
HTTP Client
Simple Explanation
Most real applications need backend data. HttpClient sends HTTP requests and receives responses.
GET reads data. POST creates data. PUT updates data. PATCH partially updates data. DELETE removes data.
HttpClient returns Observables, so you use subscribe, async pipe, or RxJS operators.
Syntax
provideHttpClient()
this.http.get<T>(url)Example
Example
export class StudentApiService {
private http = inject(HttpClient);
getStudents() {
return this.http.get<Student[]>('/api/students');
}
createStudent(request: CreateStudentRequest) {
return this.http.post<Student>('/api/students', request);
}
}
Output
Try it Yourself
Create API service.Example Explained
| Word / Code | Meaning |
|---|---|
| provideHttpClient | Registers HTTP support. |
| HttpClient | Service for API calls. |
| get<Student[]> | Typed GET request. |
| post | Sends request body. |
| Observable | Async response stream. |
Common Mistakes
- Forgetting provideHttpClient.
- No error handling.
- No loading state.
- Hard-coding API URLs everywhere.
- No TypeScript interfaces for response data.
Business Use Case
An admin dashboard uses HttpClient to load users, create projects, update status, and delete records.
Real-Time Scenario
A support ticket dashboard uses HttpClient to load tickets, create new tickets, update status, and delete closed tickets.
Practice Exercises
Do these tasks:
- Create API service.
- Add GET method.
- Add POST method.
- Display loading and error states.
Quick Interview Answer
HttpClient is used to call backend APIs from Angular.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_http.asp
- Official Link: https://angular.dev/guide/http
Angular Pipes
Simple Explanation
Pipes are mainly for formatting. Built-in pipes include date, currency, uppercase, lowercase, percent, decimal, and json.
Custom pipes can convert status codes into readable text or format repeated display values.
Pipes should not fetch data or contain heavy business logic.
Syntax
{{ value | pipeName }}Example
Example
<p>{{ amount | currency:'INR' }}</p>
<p>{{ today | date:'mediumDate' }}</p>
<p>{{ name | uppercase }}</p>
Output
Try it Yourself
Use date pipe.Example Explained
| Word / Code | Meaning |
|---|---|
| date | Formats date values. |
| currency | Formats money. |
| uppercase | Converts text to uppercase. |
| custom pipe | Developer-created display transformer. |
Common Mistakes
- Using pipes for API calls.
- Putting heavy calculations in pipes.
- Showing json pipe in final UI.
- Forgetting localization requirements.
Business Use Case
Billing, invoice, and reporting pages use pipes for dates, money, percentages, and labels.
Real-Time Scenario
A billing screen uses currency pipe for amount, date pipe for invoice date, and a custom pipe for payment status label.
Practice Exercises
Do these tasks:
- Use date pipe.
- Use currency pipe.
- Create status label pipe.
- Use pipe inside a list.
Quick Interview Answer
Pipes format values before showing them in the template.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_pipes.asp
- Official Link: https://angular.dev/guide/templates/pipes
Lifecycle Hooks
Simple Explanation
A component is created, initialized, displayed, updated, and destroyed. Hooks let you run code during these moments.
ngOnInit is commonly used for initialization. ngOnDestroy is used for cleanup. AfterViewInit is used when the component view is ready.
Good cleanup prevents memory leaks.
Syntax
ngOnInit() {}
ngOnDestroy() {}Example
Example
export class TimerComponent implements OnInit, OnDestroy {
private timerId: any;
ngOnInit() {
this.timerId = setInterval(() => console.log('tick'), 1000);
}
ngOnDestroy() {
clearInterval(this.timerId);
}
}
Output
Try it Yourself
Log lifecycle hooks.Example Explained
| Word / Code | Meaning |
|---|---|
| ngOnInit | Runs after initialization. |
| ngOnDestroy | Runs before destruction. |
| AfterViewInit | Runs after view is ready. |
| cleanup | Stopping timers/subscriptions/resources. |
Common Mistakes
- Doing heavy work in constructor.
- Forgetting cleanup.
- Accessing ViewChild too early.
- Subscribing without unsubscribe strategy.
Business Use Case
A notification panel can start listening for updates on open and clean up on close.
Real-Time Scenario
A notification component starts a timer or subscription when opened and cleans it up when the user navigates away.
Practice Exercises
Do these tasks:
- Log lifecycle hooks.
- Create timer.
- Clean timer on destroy.
- Explain constructor vs ngOnInit.
Quick Interview Answer
Lifecycle hooks let components run code at specific life stages.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_lifecycle.asp
- Official Link: https://angular.dev/guide/components/lifecycle
Angular Styling
Simple Explanation
Angular components can have their own styles. This keeps styles close to the component and reduces conflicts.
Global styles are useful for typography, layout, colors, and common utilities. Component styles are useful for local UI design.
Angular also supports class binding and style binding for dynamic visual changes.
Syntax
styles: [`h1 { color: red; }`]
styleUrl: './component.css'
[class.active]='isActive'
[style.width.%]='percent'Example
Example
@Component({
standalone: true,
template: `<p [class.active]='isActive'>Status</p>`,
styles: [`.active { font-weight: bold; }`]
})
export class StatusComponent {
isActive = true;
}
Output
Try it Yourself
Add component CSS.Example Explained
| Word / Code | Meaning |
|---|---|
| styles | Inline component CSS. |
| styleUrl | External CSS file. |
| [class.active] | Dynamic class binding. |
| [style.width.%] | Dynamic style binding. |
Common Mistakes
- Putting all styles globally.
- Using broad selectors that affect other components.
- Too much inline styling.
- No responsive design.
Business Use Case
A reusable card component can keep card-specific styles inside the component file.
Real-Time Scenario
A reusable status badge component changes class based on Active, Pending, Failed, or Blocked status.
Practice Exercises
Do these tasks:
- Add component CSS.
- Add class binding.
- Add style binding.
- Create responsive card layout.
Quick Interview Answer
Angular styling can be local to components or global to the app.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_styling.asp
- Official Link: https://angular.dev/guide/components/styling
App Bootstrap
Simple Explanation
Modern Angular applications commonly use bootstrapApplication. This function starts the root component and applies providers such as router and HttpClient.
App configuration is where you register global providers. If routing or HttpClient is missing, the app may fail when you use routerLink or HttpClient.
Understanding bootstrap helps debug provider errors.
Syntax
bootstrapApplication(AppComponent, appConfig)Example
Example
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes), provideHttpClient()]
};
bootstrapApplication(AppComponent, appConfig);
Output
Try it Yourself
Open main.ts.Example Explained
| Word / Code | Meaning |
|---|---|
| bootstrapApplication | Starts the app. |
| AppComponent | Root component. |
| appConfig | Application-level configuration. |
| providers | Services registered for the app. |
| provideRouter | Registers routes. |
Common Mistakes
- Forgetting provideRouter.
- Forgetting provideHttpClient.
- Putting business logic in main.ts.
- Confusing app startup with component logic.
Business Use Case
Large apps configure routing, HTTP, interceptors, error handling, and animations at startup.
Real-Time Scenario
The application starts with AppComponent and registers router, HttpClient, and interceptors at startup so all pages can use them.
Practice Exercises
Do these tasks:
- Open main.ts.
- Find bootstrapApplication.
- Add provideRouter.
- Add provideHttpClient.
Quick Interview Answer
App bootstrap is the startup process of an Angular application.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_bootstrap.asp
- Official Link: https://angular.dev/guide/components/importing
Control Flow
Simple Explanation
Modern Angular uses @if, @for, and @switch for template control flow.
Use @if for conditions, @for for lists, and @switch for multiple cases.
Control flow makes UI dynamic. Always handle loading, empty, success, and error states in real applications.
Syntax
@if (condition) { ... }
@for (item of items; track item.id) { ... }
@switch (value) { @case ('A') { ... } }Example
Example
@if (isLoading) {
<p>Loading...</p>
} @else {
@for (student of students; track student.id) {
<p>{{ student.name }}</p>
}
}
Output
Try it Yourself
Create @if example.Example Explained
| Word / Code | Meaning |
|---|---|
| @if | Condition. |
| @for | Loop. |
| @switch | Multiple cases. |
| track | List identity. |
| @else | Alternative block. |
Common Mistakes
- No track value in lists.
- No empty state.
- Complex business rules in template.
- Mixing old and new syntax without understanding.
Business Use Case
A dashboard can show loading state first, then a table, and use @switch for status badges.
Real-Time Scenario
A dashboard first shows loading, then either an empty state or a list of project cards, and uses switch logic for project status.
Practice Exercises
Do these tasks:
- Create @if example.
- Create @for list.
- Create @switch status.
- Add empty state.
Quick Interview Answer
Control flow controls which template blocks appear.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_control_flow.asp
- Official Link: https://angular.dev/guide/templates/control-flow
Signals
Simple Explanation
Signals are useful for local UI state and derived values. You read a signal by calling it like a function. You update it with set or update.
computed creates a derived signal. effect runs side-effect logic when signals change.
Signals are easier for many local state cases such as counters, filters, selected tabs, and loading flags.
Syntax
count = signal(0);
count();
count.set(5);
count.update(v => v + 1);
double = computed(() => count() * 2);Example
Example
count = signal(0);
doubleCount = computed(() => this.count() * 2);
increase() {
this.count.update(value => value + 1);
}
Output
Try it Yourself
Create counter signal.Example Explained
| Word / Code | Meaning |
|---|---|
| signal | Reactive state value. |
| count() | Reads signal value. |
| set | Replaces value. |
| update | Updates using old value. |
| computed | Derived value. |
Common Mistakes
- Forgetting parentheses when reading signal.
- Mutating arrays without updating the signal value.
- Using effect for derived state instead of computed.
- Mixing signals and Observables without clear reason.
Business Use Case
A cart page can store cart items in a signal and compute total price automatically.
Real-Time Scenario
A shopping cart stores item quantity in a signal and automatically updates total price using computed signals.
Practice Exercises
Do these tasks:
- Create counter signal.
- Create computed double.
- Create loading signal.
- Build cart total signal.
Quick Interview Answer
Signals provide simple reactive state in Angular.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_signals.asp
- Official Link: https://angular.dev/guide/signals
Change Detection
Simple Explanation
When component data changes, Angular checks what changed and updates the DOM.
For small apps, change detection works automatically. For large apps, performance can improve with OnPush, signals, track in lists, and avoiding heavy template functions.
Change detection is not the same as API calling. It is about keeping the UI synchronized with state.
Syntax
state changes -> Angular checks template -> DOM updatesExample
Example
@Component({
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ user.name }}</p>`
})
export class UserCardComponent {
@Input() user!: User;
}
Output
Try it Yourself
Create simple state update.Example Explained
| Word / Code | Meaning |
|---|---|
| Change detection | UI update process. |
| DOM | Browser document structure. |
| OnPush | Optimized checking strategy. |
| signals | Reactive values that help precise updates. |
| track | Improves list updates. |
Common Mistakes
- Calling heavy methods in templates.
- Mutating objects with OnPush without changing reference.
- No track in big lists.
- Optimizing without measuring.
Business Use Case
A table with hundreds of rows benefits from track values and optimized child components.
Real-Time Scenario
A large table uses track values and optimized child components so changing one row does not unnecessarily redraw the full page.
Practice Exercises
Do these tasks:
- Create simple state update.
- Use track in list.
- Try OnPush component.
- Avoid function calls in template.
Quick Interview Answer
Change detection keeps the template updated when state changes.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_change_detection.asp
- Official Link: https://angular.dev/guide/components
Dynamic Components
Simple Explanation
Normally components are written directly in templates. Dynamic components are chosen at runtime. This is useful for dialogs, dashboards, plugin-like layouts, tabs, widgets, and form builders.
Use dynamic components when the component type is not known until runtime.
For beginners, learn normal component composition first.
Syntax
Create or render a component based on runtime value.Example
Example
const componentMap = {
chart: ChartWidgetComponent,
table: TableWidgetComponent
};
selectedWidget = componentMap[this.widgetType];
Output
Try it Yourself
Create two widget components.Example Explained
| Word / Code | Meaning |
|---|---|
| dynamic component | Component chosen at runtime. |
| widget | Reusable screen block. |
| component map | Object that maps keys to components. |
| runtime | When app is running. |
Common Mistakes
- Using dynamic components when simple @if is enough.
- Creating overly complex widget systems.
- No clear input/output contract.
- Hard-to-debug dynamic layouts.
Business Use Case
A customizable admin dashboard can load chart, table, KPI, and alert widgets dynamically.
Real-Time Scenario
A customizable dashboard loads chart widgets, table widgets, KPI widgets, or alert widgets based on the user's dashboard configuration.
Practice Exercises
Do these tasks:
- Create two widget components.
- Select component based on type.
- Pass input data.
- Compare with @switch.
Quick Interview Answer
Dynamic components allow runtime component selection.
Reference Links
Advanced DI
Simple Explanation
Normal services use providedIn root. Advanced DI is needed when you want to inject configuration values, choose different implementations, or create services with factories.
InjectionToken is useful for values like API base URL or app config.
Provider scope matters. Providing a service at root gives one shared instance. Providing at component level creates separate instances.
Syntax
new InjectionToken<T>('TOKEN')
{ provide: TOKEN, useValue: value }
{ provide: Service, useClass: OtherService }Example
Example
export const API_BASE_URL = new InjectionToken<string>('API_BASE_URL');
export const appConfig = {
providers: [
{ provide: API_BASE_URL, useValue: 'https://api.example.com' }
]
};
baseUrl = inject(API_BASE_URL);
Output
Try it Yourself
Create API_BASE_URL token.Example Explained
| Word / Code | Meaning |
|---|---|
| InjectionToken | Token for injecting non-class values. |
| useValue | Provides a fixed value. |
| useClass | Provides another class implementation. |
| useFactory | Creates value using a function. |
| provider scope | Where service instance is created. |
Common Mistakes
- Hard-coding config values everywhere.
- Using root provider when isolated instance is needed.
- Forgetting to provide InjectionToken.
- Making DI too complex too early.
Business Use Case
A multi-environment app can inject API_BASE_URL so services do not hard-code URLs.
Real-Time Scenario
An API base URL is provided through an InjectionToken so the same app can run against dev, QA, and production APIs.
Practice Exercises
Do these tasks:
- Create API_BASE_URL token.
- Inject it into service.
- Try component-level provider.
- Write provider scope notes.
Quick Interview Answer
Advanced DI customizes how dependencies are provided and injected.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_advanced_di.asp
- Official Link: https://angular.dev/guide/di
Router Advanced
Simple Explanation
Large applications need more than simple routes. Child routes create nested pages. Lazy loading improves performance. Guards protect routes. Resolvers fetch required data. Query parameters store filters.
Advanced routing helps structure real business portals.
Do not overuse guards or resolvers. Keep navigation predictable.
Syntax
children: [...]
canActivate: [...]
resolve: {...}
queryParams: {...}Example
Example
{
path: 'customers/:id',
component: CustomerLayoutComponent,
children: [
{ path: 'overview', component: CustomerOverviewComponent },
{ path: 'orders', component: CustomerOrdersComponent }
]
}
Output
Try it Yourself
Create child routes.Example Explained
| Word / Code | Meaning |
|---|---|
| children | Nested routes. |
| guard | Controls access. |
| resolver | Loads data before route activation. |
| query params | Optional URL filters. |
| lazy loading | Loads feature code later. |
Common Mistakes
- No child RouterOutlet.
- Wrong relative links.
- Resolver blocks navigation without error handling.
- Query params not synced with filters.
Business Use Case
A customer details page can have child tabs: overview, orders, tickets, notes, and documents.
Real-Time Scenario
A customer details route has child tabs for overview, orders, tickets, notes, and documents with nested routing.
Practice Exercises
Do these tasks:
- Create child routes.
- Add query params.
- Create auth guard.
- Lazy load admin route.
Quick Interview Answer
Advanced routing structures large Angular applications.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_router_advanced.asp
- Official Link: https://angular.dev/guide/routing
HTTP Interceptors
Simple Explanation
Interceptors are used for authentication headers, error handling, logging, retry logic, and global loading indicators.
Requests are immutable, so you clone a request before modifying it.
Keep interceptors focused. One interceptor should not handle every possible concern.
Syntax
export const interceptor: HttpInterceptorFn = (req, next) => next(req);Example
Example
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = localStorage.getItem('token');
const authReq = token
? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } })
: req;
return next(authReq);
};
Output
Try it Yourself
Create auth interceptor.Example Explained
| Word / Code | Meaning |
|---|---|
| HttpInterceptorFn | Functional interceptor type. |
| req.clone | Copies request with changes. |
| setHeaders | Adds headers. |
| next | Passes request to next handler. |
| Authorization | Common auth header. |
Common Mistakes
- Mutating request directly.
- Interceptor not registered.
- Adding tokens to external URLs.
- No 401/403 handling.
- Storing tokens carelessly.
Business Use Case
Enterprise applications use interceptors to attach tokens and handle common API errors consistently.
Real-Time Scenario
An auth interceptor automatically attaches a JWT token to backend API requests and redirects the user on 401 unauthorized responses.
Practice Exercises
Do these tasks:
- Create auth interceptor.
- Add custom header.
- Handle 401 response.
- Check Network tab.
Quick Interview Answer
HTTP interceptors apply shared behavior to API requests and responses.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_http_interceptors.asp
- Official Link: https://angular.dev/guide/http/interceptors
Forms Advanced
Simple Explanation
Business forms can be complex. They may have repeating sections, conditional fields, custom validation, backend validation, and reusable custom controls.
FormArray is used for dynamic lists like skills, addresses, phone numbers, project members, or uploaded documents.
ControlValueAccessor is used when a custom component should behave like a normal form control.
Syntax
new FormArray([])
customValidator(control)
ControlValueAccessorExample
Example
form = new FormGroup({
skills: new FormArray<FormControl<string>>([])
});
addSkill() {
this.form.controls.skills.push(new FormControl('', { nonNullable: true }));
}
Output
Try it Yourself
Create FormArray.Example Explained
| Word / Code | Meaning |
|---|---|
| FormArray | Dynamic list of controls. |
| custom validator | Developer-defined validation rule. |
| async validator | Validation that may call backend. |
| ControlValueAccessor | Connects custom component to Angular forms. |
Common Mistakes
- Using plain arrays outside form model.
- No validation for dynamic rows.
- Template becomes too complex.
- Custom control not reporting touched/changed state.
Business Use Case
A resume form may allow multiple skills, education entries, work experiences, and document uploads.
Real-Time Scenario
A resume builder form lets users add multiple skills, education records, work experiences, and document uploads dynamically.
Practice Exercises
Do these tasks:
- Create FormArray.
- Add and remove rows.
- Create password match validator.
- Build simple custom rating control.
Quick Interview Answer
Advanced forms handle complex and dynamic business input.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_forms_advanced.asp
- Official Link: https://angular.dev/guide/forms/reactive-forms
State Management
Simple Explanation
Small state can stay inside a component. Shared state can go into a service. Complex app-wide state may use a structured store pattern.
Signals are useful for simple state in components and services. Observables are useful for async streams. State libraries can help with large complex applications.
Choose the simplest approach that solves the problem.
Syntax
component state -> service state -> app storeExample
Example
@Injectable({ providedIn: 'root' })
export class CartService {
private items = signal<CartItem[]>([]);
cartItems = this.items.asReadonly();
total = computed(() => this.items().reduce((sum, item) => sum + item.price * item.qty, 0));
add(item: CartItem) {
this.items.update(items => [...items, item]);
}
}
Output
Try it Yourself
Create CartService.Example Explained
| Word / Code | Meaning |
|---|---|
| component state | Data needed by one component. |
| service state | Shared data. |
| store | Structured app-wide state. |
| signal | Reactive local/shared state. |
| computed | Derived state. |
Common Mistakes
- Global state for every small value.
- Duplicating the same state in many places.
- No clear source of truth.
- Adding heavy state libraries too early.
Business Use Case
E-commerce cart state is needed in product page, header, cart page, and checkout, so service state is useful.
Real-Time Scenario
A cart service shares selected cart items across product page, header cart count, cart page, and checkout page.
Practice Exercises
Do these tasks:
- Create CartService.
- Add item.
- Compute total.
- Show cart count in header.
Quick Interview Answer
State management controls where data lives and how it changes.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_state_management.asp
- Official Link: https://angular.dev/guide/signals
Animations
Simple Explanation
Animations can make UI changes easier to understand. Examples include fade in, slide, expand, collapse, route transitions, alert enter/leave, and modal opening.
Use animations carefully. Too many animations can slow the app or distract users.
Good animations are short, meaningful, and accessible.
Syntax
trigger('name', [transition(...), animate(...)])Example
Example
animations: [
trigger('fade', [
transition(':enter', [style({ opacity: 0 }), animate('200ms', style({ opacity: 1 }))]),
transition(':leave', [animate('200ms', style({ opacity: 0 }))])
])
]
// template
// <div @fade>Saved successfully</div>
Output
Try it Yourself
Create fade animation.Example Explained
| Word / Code | Meaning |
|---|---|
| trigger | Animation name. |
| transition | Change from one state to another. |
| style | CSS state. |
| animate | Timing and final state. |
| :enter/:leave | Element added or removed. |
Common Mistakes
- Animating everything.
- Animations too slow.
- No reduced-motion consideration.
- Forgetting animation setup.
- Using animation to hide bad UX.
Business Use Case
A notification alert can fade in after save and fade out after a few seconds.
Real-Time Scenario
A save-success alert fades in after the user saves a form and fades out automatically after a few seconds.
Practice Exercises
Do these tasks:
- Create fade animation.
- Animate list items.
- Animate expand/collapse panel.
- Keep animation under 300ms.
Quick Interview Answer
Animations help users understand UI changes.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_animations.asp
- Official Link: https://angular.dev/guide/animations
Testing
Simple Explanation
Testing helps catch bugs before users see them. Component tests check UI behavior. Service tests check logic. HTTP tests check API service methods without real backend calls.
Start with simple tests: component creation, displayed title, button click, form validation, and service method.
Good tests focus on behavior, not implementation details.
Syntax
ng test
TestBed.configureTestingModule({...})Example
Example
describe('AppComponent', () => {
it('should create', async () => {
await TestBed.configureTestingModule({ imports: [AppComponent] }).compileComponents();
const fixture = TestBed.createComponent(AppComponent);
expect(fixture.componentInstance).toBeTruthy();
});
});
Output
Try it Yourself
Run ng test.Example Explained
| Word / Code | Meaning |
|---|---|
| TestBed | Angular testing environment. |
| fixture | Component test wrapper. |
| expect | Assertion. |
| mock service | Fake service for tests. |
| ng test | Runs tests. |
Common Mistakes
- Only testing component creation.
- Not mocking API services.
- Forgetting detectChanges.
- Testing private implementation details too much.
Business Use Case
A login form should have tests for required validation, invalid email, submit button disabled state, and success call.
Real-Time Scenario
A login form test checks that the Submit button is disabled when email is invalid and enabled when the form becomes valid.
Practice Exercises
Do these tasks:
- Run ng test.
- Test displayed title.
- Test button click.
- Test service method.
- Test form validation.
Quick Interview Answer
Angular testing verifies app behavior before release.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_testing.asp
- Official Link: https://angular.dev/guide/testing
Security
Simple Explanation
Angular helps protect against some XSS risks by treating template values as untrusted. But developers can still create vulnerabilities.
Be careful with innerHTML and any sanitizer bypass method. Do not put secrets in frontend files. Anything in browser JavaScript can be viewed by users.
Route guards are not full security. Backend APIs must verify permissions.
Syntax
Never trust user input.
Do not store secrets in frontend.
Backend must authorize every protected action.Example
Example
<p>{{ userComment }}</p>
<!-- Use carefully -->
<div [innerHTML]='htmlContent'></div>
Output
Try it Yourself
Explain XSS.Example Explained
| Word / Code | Meaning |
|---|---|
| XSS | Malicious script injection. |
| sanitization | Cleaning unsafe values. |
| innerHTML | Can be risky with untrusted HTML. |
| route guard | Frontend navigation check. |
| backend authorization | Real permission enforcement. |
Common Mistakes
- Using bypassSecurityTrust casually.
- Putting API secrets in Angular environment files.
- Depending only on route guards.
- Displaying raw backend error details.
Business Use Case
A banking or healthcare app must protect user data with safe rendering, secure sessions, and backend authorization.
Real-Time Scenario
A banking application never trusts route guards alone; the backend verifies every protected API request even if the Angular screen is hidden.
Practice Exercises
Do these tasks:
- Explain XSS.
- Find innerHTML usage.
- Explain frontend guard vs backend security.
- Write token storage rules.
Quick Interview Answer
Angular security requires safe templates and backend authorization.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_security.asp
- Official Link: https://angular.dev/best-practices/security
SSR and Hydration
Simple Explanation
Normal Angular apps render in the browser. SSR can send ready HTML from the server. This may improve first load and SEO for public pages.
Hydration allows Angular to reuse server-rendered HTML instead of recreating everything.
SSR adds complexity. Browser-only APIs like window, document, and localStorage need careful handling.
Syntax
ng add @angular/ssr
npm run buildExample
Example
// Avoid direct browser-only code during SSR
if (typeof window !== 'undefined') {
console.log(window.location.href);
}
Output
Try it Yourself
Add SSR to a demo app.Example Explained
| Word / Code | Meaning |
|---|---|
| SSR | Server-side rendering. |
| hydration | Reusing server HTML in browser. |
| prerender | Generate static HTML at build time. |
| browser-only API | window, document, localStorage. |
| SEO | Search engine visibility. |
Common Mistakes
- Adding SSR without need.
- Using window/localStorage directly during server rendering.
- Hydration mismatch.
- Not testing production build.
Business Use Case
A public course catalog or product page may use SSR for faster first content and better indexing.
Real-Time Scenario
A public course catalog uses server-side rendering so search engines and users receive meaningful HTML quickly.
Practice Exercises
Do these tasks:
- Add SSR to a demo app.
- Build the app.
- Find browser-only code.
- Write SSR pros and cons.
Quick Interview Answer
SSR renders Angular HTML on the server and hydration makes it interactive.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_ssr.asp
- Official Link: https://angular.dev/guide/ssr
Angular Exercises
Simple Explanation
Angular is best learned by doing. Reading is not enough. After every topic, write code, break it, fix it, and explain it.
A useful exercise should have a small goal, expected output, common mistake, and explanation.
Your notebook should include definitions, syntax, examples, errors, and fixes.
Syntax
Read topic -> write code -> run -> change -> debug -> explainExample
Example
// Example exercise
// Create a component with name and course properties
// Display both using interpolation
// Add a button that changes the course
Output
Try it Yourself
Create one component exercise.Example Explained
| Word / Code | Meaning |
|---|---|
| exercise | Hands-on practice task. |
| expected output | What should appear. |
| debugging | Fixing errors. |
| notebook | Your personal study notes. |
| practice project | Small app built from exercises. |
Common Mistakes
- Only reading without coding.
- Copying code without changing it.
- Not writing errors and fixes.
- Skipping browser console errors.
Business Use Case
Training batches can use exercises after each topic to make sure students understand components, forms, routing, and HTTP.
Real-Time Scenario
A training batch completes one small coding task after each topic, records errors, fixes them, and adds screenshots to a learning notebook.
Practice Exercises
Do these tasks:
- Create one component exercise.
- Create one form exercise.
- Create one route exercise.
- Create one HTTP service exercise.
Quick Interview Answer
Exercises turn Angular theory into practical skill.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/angular_exercises.asp
- Official Link: https://angular.dev/tutorials
Project 1: Student Management App
Simple Explanation
This project should have a dashboard, student list, student details, create/edit form, search box, and reusable student card or table.
Start with mock data in StudentService. After the UI works, replace mock data with HttpClient.
This project is good for interviews because it proves you can build a real business-style frontend.
Syntax
Dashboard + List + Details + Form + Service + RoutesExample
Example
ng generate component features/students/student-list
ng generate component features/students/student-details
ng generate component features/students/student-form
ng generate service features/students/student
Output
Try it Yourself
Create student routes.Example Explained
| Word / Code | Meaning |
|---|---|
| student-list | Displays students. |
| student-details | Shows one student. |
| student-form | Create/edit form. |
| student service | Data logic. |
| routes | Navigation between pages. |
Common Mistakes
- No validation.
- No folder structure.
- Hard-coded data in many components.
- No README or screenshots.
Business Use Case
Training institutes and learning platforms need student record management, course assignment, and certificate tracking.
Real-Time Scenario
A training institute uses this app to manage student records, course enrollments, active status, and basic student profile details.
Practice Exercises
Do these tasks:
- Create student routes.
- Build list page.
- Build details page.
- Build reactive form.
- Add screenshots to README.
Quick Interview Answer
This project demonstrates basic Angular application structure.
Reference Links
- Official Link: https://angular.dev/tutorials
Project 2: API CRUD Dashboard
Simple Explanation
Build a dashboard for customers, employees, products, tickets, or projects. Use HttpClient in a service. Use typed interfaces for request and response data.
Add loading states, error messages, delete confirmation, create/edit forms, and search/filter.
This project proves you understand frontend-backend integration.
Syntax
GET list
POST create
PUT/PATCH update
DELETE removeExample
Example
getItems() { return this.http.get<Item[]>('/api/items'); }
createItem(req: CreateItemRequest) { return this.http.post<Item>('/api/items', req); }
updateItem(id: number, req: UpdateItemRequest) { return this.http.put<Item>(`/api/items/${id}`, req); }
deleteItem(id: number) { return this.http.delete<void>(`/api/items/${id}`); }
Output
Try it Yourself
Build list from API.Example Explained
| Word / Code | Meaning |
|---|---|
| CRUD | Create, Read, Update, Delete. |
| HttpClient | API communication. |
| typed interface | TypeScript model for data. |
| loading state | Shows request in progress. |
| error state | Shows request failure. |
Common Mistakes
- API calls directly in many components.
- No error handling.
- No delete confirmation.
- No typed models.
- No CORS understanding.
Business Use Case
Admin dashboards for customer management, employee management, ticket management, and project management use CRUD patterns.
Real-Time Scenario
An internal admin team uses this dashboard to manage customers, employees, products, tickets, or projects through backend APIs.
Practice Exercises
Do these tasks:
- Build list from API.
- Add create form.
- Add edit form.
- Add delete confirmation.
- Add error handling.
Quick Interview Answer
This project demonstrates Angular API integration.
Reference Links
- Official Link: https://angular.dev/guide/http
Project 3: Enterprise Portal
Simple Explanation
Build a login page, dashboard layout, sidebar, profile page, admin page, and one API-backed feature page.
Use AuthService, route guards, HTTP interceptor, lazy loading, reactive forms, and reusable table/card components.
This project is closest to real company frontend work.
Syntax
Login -> AuthService -> Guard -> Shell Layout -> Feature Routes -> API ServicesExample
Example
export const routes: Routes = [
{ path: 'login', component: LoginComponent },
{
path: '',
component: ShellComponent,
canActivate: [authGuard],
children: [
{ path: 'dashboard', component: DashboardComponent },
{ path: 'admin', canActivate: [adminGuard], component: AdminComponent }
]
}
];
Output
Try it Yourself
Create login page.Example Explained
| Word / Code | Meaning |
|---|---|
| AuthService | Manages login/user state. |
| authGuard | Protects logged-in routes. |
| adminGuard | Protects admin route. |
| ShellComponent | Main layout after login. |
| interceptor | Adds token to API requests. |
Common Mistakes
- Frontend-only security.
- No backend authorization.
- No logout flow.
- No lazy loading.
- No clear folder structure.
Business Use Case
Employee portals, banking portals, and internal admin systems commonly follow this architecture.
Real-Time Scenario
A company uses this portal for login, dashboard, profile, employee data, admin screens, protected pages, and API-based operations.
Practice Exercises
Do these tasks:
- Create login page.
- Create shell layout.
- Protect dashboard route.
- Add admin guard.
- Add auth interceptor.
Quick Interview Answer
This project demonstrates enterprise Angular architecture.
Reference Links
- Official Link: https://angular.dev/guide/routing
Angular Interview Preparation
Simple Explanation
Do not memorize only definitions. Interviewers want to know whether you can build, explain, and debug Angular applications.
Use this answer format for every topic: what it is, why it is used, small code example, where you used it in a project, one common mistake, and how to fix it.
Use your own projects as proof.
Syntax
Definition -> Why used -> Code -> Project example -> Mistake -> DebuggingExample
Example
Question: What is a component?
Answer:
A component is a reusable UI block in Angular. It has a TypeScript class, template, styles, and metadata. I used StudentListComponent to display student records. A common mistake is creating one huge component, and I fix it by splitting UI into child components.
Output
Try it Yourself
Explain components.Example Explained
| Word / Code | Meaning |
|---|---|
| definition | Clear meaning. |
| use case | Why it matters. |
| code | Small example. |
| mistake | Common error. |
| debugging | How to fix problem. |
Common Mistakes
- Only memorizing definitions.
- No project examples.
- No troubleshooting examples.
- Confusing route guards with backend security.
- Not knowing forms or HTTP clearly.
Business Use Case
Companies want Angular developers who can build forms, call APIs, structure routes, debug errors, and explain code clearly.
Real-Time Scenario
Before an interview, a student revises each topic by explaining definition, syntax, project usage, common mistake, and debugging approach.
Practice Exercises
Do these tasks:
- Explain components.
- Explain services.
- Explain forms.
- Explain routing.
- Explain HttpClient and interceptors.
Quick Interview Answer
Interview answers should connect Angular concepts to real projects.
Reference Links
- Official Link: https://angular.dev/
One Page Interview Questions
How to Answer Any Angular Interview Question
Answer format: Definition -> Why it is used -> Syntax or small code example -> Business use case -> Real-time scenario -> Common mistake -> Debugging step.
Example: A component is a reusable UI block. It is used to split a large screen into smaller parts. In a student portal, StudentCardComponent can show one student. A common mistake is creating one huge component; fix it by splitting reusable child components.
One Page Angular Interview Questions and Answers
| Question | Short Answer |
|---|---|
| What is Angular? | Angular is a TypeScript-based frontend framework used to build component-based web applications. |
| What is a component? | A component is a reusable UI block with a TypeScript class, template, styles, and metadata. |
| What is a template? | A template is the HTML view of a component. |
| What is data binding? | Data binding connects component data with the template using interpolation, property binding, event binding, or two-way binding. |
| What is interpolation? | Interpolation displays component values as text using double curly braces. |
| What is property binding? | Property binding sets DOM or child component properties from component values. |
| What is event binding? | Event binding listens to user actions and calls component methods. |
| What is two-way binding? | Two-way binding keeps a form input and component property synchronized. |
| What is a directive? | A directive adds behavior to an element or changes how template content is rendered. |
| What is a pipe? | A pipe transforms a value for display, such as date, currency, uppercase, or custom status labels. |
| What is a service? | A service is a reusable class for shared logic, API calls, state, or utility functions. |
| What is dependency injection? | Dependency injection provides services or objects to classes without manually creating them. |
| What is routing? | Routing maps URLs to components so users can navigate between views. |
| What is a route guard? | A route guard decides whether navigation to a route should continue. |
| Are route guards enough for security? | No. Guards only protect frontend navigation. Backend APIs must still verify authentication and authorization. |
| What is HttpClient? | HttpClient is Angular's service for making HTTP requests to backend APIs. |
| What is an interceptor? | An interceptor modifies or observes HTTP requests and responses globally. |
| What is an Observable? | An Observable is a stream of values over time. |
| What is async pipe? | The async pipe subscribes to an Observable in the template and automatically unsubscribes. |
| What are signals? | Signals are reactive values that notify Angular when they change. |
| What is reactive form? | A reactive form defines controls and validation in TypeScript using FormGroup and FormControl. |
| What is template-driven form? | A template-driven form defines most form behavior in the template using ngModel. |
| What is lifecycle hook? | A lifecycle hook is a method Angular calls during component creation, update, or destruction. |
| What is lazy loading? | Lazy loading loads route or feature code only when needed. |
| What is track or TrackBy? | Track gives Angular a stable identity for list items, improving rendering performance. |
| What is SSR? | Server-side rendering generates Angular HTML on the server before the browser app becomes interactive. |
| What is a good project structure? | Use core for app-wide services, shared for reusable UI, features for business screens, and models for interfaces. |
| How do you debug Angular errors? | Check browser console, terminal output, imports, routes, template property names, API Network tab, and provider setup. |
| Explain a real-time Angular project. | A student management or admin dashboard with login, routes, forms, API CRUD, guards, interceptors, and reusable components is a strong example. |
| What makes a good Angular interview answer? | Give definition, purpose, syntax/example, business use case, real-time scenario, common mistake, and debugging step. |
Must-Explain Real-Time Project Flow
Project: Student Management / Admin Dashboard.
Flow: User logs in -> AuthService stores login state -> route guard protects dashboard -> dashboard route loads -> StudentService calls backend using HttpClient -> interceptor adds auth token -> list component displays students using @for -> form component validates input using reactive forms -> save button calls POST/PUT API -> success message appears -> table refreshes.
Final Practice Before Interview
- Explain components, templates, services, routing, forms, and HTTP without reading notes.
- Draw your project architecture: routes, components, services, API, guards, and interceptors.
- Prepare one bug you fixed: missing import, wrong route, API CORS, form validation, or provider error.
- Prepare one performance answer: lazy loading, track in lists, @defer, or OnPush.
- Prepare one security answer: route guards are not enough; backend authorization is required.
Reference Links
- Tutorial Link: https://www.w3schools.com/angular/
- Official Link: https://angular.dev/