Directives in Angular
Directives in Angular
In Angular, directives are used to extend the behavior of elements and components. There are three
types of directives:
1. Component Directives
2. Attribute Directives
3. Structural Directives
1. Component Directives
A component is a special type of directive that includes a template (HTML), styles, and logic.
Example:
typescript
@Component({
selector: 'app-example',
template: `<h2>Hello, Angular!</h2>`,
styles: ['h2 { color: blue; }']
})
export class ExampleComponent { }
Key Features:
2. Attribute Directives
Modify the appearance or behavior of an element, component, or another directive.
1/411
ngClass – Adds/removes CSS classes dynamically.
Example:
html
typescript
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective {
constructor(private el: ElementRef) {
el.nativeElement.style.backgroundColor = 'yellow';
}
}
Key Features:
3. Structural Directives
Modify the structure of the DOM by adding or removing elements.
Example:
html
2/411
<div *ngIf="isVisible">This text is conditionally visible</div>
typescript
@Directive({
selector: '[appIf]'
})
export class CustomIfDirective {
@Input() set appIf(condition: boolean) {
if (!condition) {
this.viewContainer.clear();
} else {
this.viewContainer.createEmbeddedView(this.templateRef);
}
}
Key Features:
Structural Modifies the structure of the DOM (add/remove *ngIf , *ngFor , *appIf
Directive elements)
3/411
Pipes?
Q30. What is Chaining Pipes?
Types of Decorators:
1. Class Decorators
typescript
@Component({
selector: 'app-example',
template: `<h2>Hello, Angular!</h2>`
})
export class ExampleComponent { }
2. Property Decorators
Example:
typescript
3. Method Decorators
Example: @HostListener()
Example:
typescript
@Directive({
selector: '[appClickListener]'
4/411
})
export class ClickListenerDirective {
@HostListener('click') onClick() {
alert('Element clicked!');
}
}
4. Parameter Decorators
Example:
typescript
Q29. What are Pipes? What are the types of Pipes & Parameterized Pipes?
Pipes in Angular:
Pipes transform data into a desired format in templates without changing the original data.
Types of Pipes:
Example:
html
5/411
<p>{{ today | date: 'short' }}</p>
<p>{{ price | currency: 'INR' }}</p>
typescript
Usage in HTML:
html
Parameterized Pipes:
Example:
html
Example:
html
6/411
Output: ANGULAR
Services in Angular
In Angular, a service is a reusable class that provides business logic, data handling, and shared
functionality across multiple components.
Example of a Service:
typescript
@Injectable({
providedIn: 'root' // Service is available throughout the app
})
export class DataService {
private data: string = 'Angular Service Data';
getData(): string {
return this.data;
}
}
7/411
Using the Service in a Component
typescript
@Component({
selector: 'app-example',
template: `<h2>{{ data }}</h2>`
})
export class ExampleComponent {
data: string;
sh
or
sh
ng g s service-name
sh
ng g s user
typescript
8/411
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UserService {
getUser(): string {
return 'John Doe';
}
}
typescript
@Component({
selector: 'app-user',
template: `<p>User: {{ user }}</p>`
})
export class UserComponent {
user: string;
9/411
Q34: What is Hierarchical Dependency Injection?
Hierarchical Dependency Injection (DI) is the way Angular manages service instances based on
module and component trees.
Levels of DI:
Example of Component-Level DI
typescript
@Component({
selector: 'app-child',
template: `<p>Child Component</p>`,
providers: [UserService] // Provides a new instance for this component
})
export class ChildComponent {
constructor(private userService: UserService) { }
}
Types of Providers:
typescript
10/411
providers: [UserService]
2. Value Provider
typescript
3. Factory Provider
typescript
4. Aliased Provider
typescript
Roles of @Injectable :
typescript
@Injectable({
providedIn: 'root'
})
export class AuthService {
isAuthenticated(): boolean {
return true;
11/411
}
}
Communication between them is done using @Input() (for passing data) and @Output() (for
sending events).
html
<app-child [childMessage]="parentMessage"></app-child>
typescript
@Component({
12/411
selector: 'app-child',
template: `<p>Message from parent: {{ childMessage }}</p>`
})
export class ChildComponent {
@Input() childMessage!: string; // Receiving data from parent
}
Parent Component
typescript
@Component({
selector: 'app-parent',
template: `<app-child [childMessage]="message"></app-child>`
})
export class ParentComponent {
message = 'Hello from Parent!';
}
Child Component
typescript
@Component({
selector: 'app-child',
template: `<p>Received: {{ childMessage }}</p>`
})
export class ChildComponent {
13/411
@Input() childMessage!: string;
}
Child Component
typescript
@Component({
selector: 'app-child',
template: `<button (click)="sendMessage()">Send Message</button>`
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit('Hello from Child!');
}
}
Parent Component
typescript
@Component({
selector: 'app-parent',
template: `<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>Message: {{ message }}</p>`
})
export class ParentComponent {
message = '';
14/411
receiveMessage(event: string) {
this.message = event;
}
}
Used for dependency injection but should not contain heavy logic.
Example:
typescript
15/411
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
template: `<p>Constructor Example</p>`
})
export class ExampleComponent {
constructor() {
console.log('Constructor called!');
}
}
Example:
typescript
@Component({
selector: 'app-child',
template: `<p>Value: {{ value }}</p>`
})
export class ChildComponent implements OnChanges {
@Input() value!: string;
ngOnChanges(changes: SimpleChanges) {
console.log('Changes detected:', changes);
}
}
16/411
ngOnInit()
Example:
typescript
@Component({
selector: 'app-example',
template: `<p>ngOnInit Example</p>`
})
export class ExampleComponent implements OnInit {
ngOnInit() {
console.log('ngOnInit called!');
}
}
Execution Time Called when the class is Called after the constructor and after component
instantiated. initialization.
Purpose Used for dependency injection. Used for initialization logic (like fetching API data).
Usage Should not include complex logic. Good for API calls, subscriptions, and initialization
logic.
Example Comparison:
typescript
17/411
ngOnInit() {
console.log('ngOnInit: Component Initialized!');
}
}
Output:
vbnet
Key Points:
It defines where the routed components should be displayed.
It works with Angular’s Router Module for Single Page Applications (SPA).
You can have multiple router-outlet instances (e.g., for child routes).
typescript
18/411
{ path: 'home', component: HomeComponent },
{ path: 'about', component: AboutComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' } // Default route
];
@NgModule({
declarations: [AppComponent, HomeComponent, AboutComponent],
imports: [BrowserModule, RouterModule.forRoot(routes)],
bootstrap: [AppComponent]
})
export class AppModule { }
html
<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
</nav>
<hr>
<router-outlet></router-outlet> <!-- Dynamic component rendering -->
html
<nav>
<a routerLink="/home">Home</a>
<a routerLink="/about">About</a>
</nav>
<router-outlet></router-outlet>
19/411
html
css
.active {
font-weight: bold;
color: blue;
}
typescript
goToHome() {
this.router.navigate(['/home']);
}
typescript
20/411
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { ParentComponent } from './parent.component';
import { ChildOneComponent } from './child-one.component';
import { ChildTwoComponent } from './child-two.component';
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
html
<h2>Parent Component</h2>
<nav>
<a routerLink="child-one">Child One</a> |
<a routerLink="child-two">Child Two</a>
</nav>
21/411
Step 3: Child Components
child-one.component.html
html
child-two.component.html
html
🔹 Result:
Visiting /parent loads the ParentComponent, and clicking the links loads either ChildOneComponent
or ChildTwoComponent inside the parent.
sh
typescript
22/411
import { FeatureComponent } from './feature.component';
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class FeatureRoutingModule { }
typescript
🔹 Result:
The feature.module.ts is not loaded initially.
It loads only when the user navigates to /feature , reducing initial load time.
📝 Summary
Feature Purpose
Lazy Loading Loads feature modules only when needed, optimizing performance.
23/411
Route Guards in Angular (Authentication-Based Navigation)
Route Guards in Angular control access to routes based on conditions, such as authentication or role-
based access.
Guard Purpose
CanDeactivate Prevents navigation away from a route (e.g., unsaved changes warning).
For authentication, the most commonly used guards are CanActivate and CanLoad .
This guard restricts access to a route if the user is not logged in.
typescript
@Injectable({
providedIn: 'root'
})
export class AuthService {
private isLoggedIn = false; // Change to true after successful login
login() {
this.isLoggedIn = true;
}
24/411
logout() {
this.isLoggedIn = false;
}
isAuthenticated(): boolean {
return this.isLoggedIn;
}
}
sh
typescript
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (this.authService.isAuthenticated()) {
return true;
} else {
this.router.navigate(['/login']); // Redirect to login page
return false;
}
}
}
25/411
Step 3: Protect Routes Using CanActivate
Modify app-routing.module.ts to apply the guard:
typescript
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
typescript
@Component({
selector: 'app-login',
template: `
<h2>Login Page</h2>
<button (click)="login()">Login</button>
`
})
export class LoginComponent {
constructor(private authService: AuthService, private router: Router) {}
26/411
login() {
this.authService.login();
this.router.navigate(['/dashboard']); // Redirect after login
}
}
CanLoad prevents an entire module from being loaded if the user is not authenticated.
This improves security and performance by preventing unauthorized users from even loading the
code.
typescript
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate, CanLoad {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
return this.checkLogin();
}
canLoad(): boolean {
return this.checkLogin();
}
27/411
}
}
typescript
4️⃣ Summary
Feature Purpose
🔹 Final Flow:
1️⃣ If the user is not logged in, they are redirected to .
/login
2️⃣ After clicking "Login", they are redirected to /dashboard.
3️⃣ If they try to access/dashboard directly without logging in, they are blocked.
4️⃣ If CanLoadis used, lazy modules won't even be downloaded for unauthorized users.
Would you like an example for role-based access (e.g., Admin vs User)? 🚀
28/411
02:33
Q51. What is Observable? How to implement Observable ?
04:48
Q52. What is the role of HttpClient in Angular?
01:16
Q53. What are the steps for fetching the data with HttpClient &
Observable ?
08:46
Q54. How to do HTTP Error Handling in Angular ?
Handling Multiple Returns only one value. Emits multiple values over time.
Values
Operators Supports .then() and Supports powerful RxJS operators like map() ,
.catch() . filter() , retry() , etc.
Use Case Ideal for one-time API calls. Ideal for streams of data, WebSockets, or user events.
🔹 Example of a Promise:
typescript
🔹 Example of an Observable:
typescript
29/411
// Unsubscribe after 5 seconds
setTimeout(() => subscription.unsubscribe(), 5000);
🔹 Key Features:
Provides Observables, Operators, and Subscriptions.
Allows data transformation with operators like map() , filter() , merge() , etc.
Output: 4, 8, 12
typescript
30/411
});
Output:
scss
Value 1
Value 2
(Value 3 appears after 2 seconds)
🔹 Key Features:
Supports Observables for handling HTTP requests.
typescript
@NgModule({
imports: [HttpClientModule]
})
export class AppModule { }
31/411
typescript
@Injectable({
providedIn: 'root'
})
export class ApiService {
private apiUrl = 'https://jsonplaceholder.typicode.com/posts';
getPosts(): Observable<any> {
return this.http.get(this.apiUrl);
}
}
typescript
@Component({
selector: 'app-posts',
template: `<ul><li *ngFor="let post of posts">{{ post.title }}</li></ul>`
})
export class PostsComponent implements OnInit {
posts: any[] = [];
ngOnInit() {
this.apiService.getPosts().subscribe(data => this.posts = data);
}
}
32/411
To handle HTTP errors, use RxJS operators like catchError() .
typescript
getPosts(): Observable<any> {
return this.http.get(this.apiUrl).pipe(
catchError(error => {
console.error("Error fetching data:", error);
return throwError(() => new Error("Something went wrong!"));
})
);
}
typescript
ngOnInit() {
this.apiService.getPosts().subscribe({
next: data => this.posts = data,
error: err => console.error("Error:", err.message)
});
}
Summary
Concept Explanation
Promise vs Observable Promises return one value; Observables handle multiple values.
RxJS A reactive programming library used for handling async data streams.
33/411
Here’s a real-world example of fetching paginated API data using HttpClient , Observables , and
error handling in Angular.
json
{
"posts": [
{ "id": 1, "title": "Angular Basics", "content": "Learn Angular step by step" },
{ "id": 2, "title": "RxJS in Angular", "content": "Understanding Observables" },
{ "id": 3, "title": "HttpClient Usage", "content": "Making API calls in Angular" },
{ "id": 4, "title": "Pagination in Angular", "content": "Implementing load more
functionality" }
]
}
typescript
34/411
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, HttpClientModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
typescript
@Injectable({
providedIn: 'root'
})
export class PostService {
private apiUrl = 'http://localhost:3000/posts';
35/411
}
}
typescript
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
posts: any[] = [];
page = 1;
limit = 2; // Load 2 posts per page
isLoading = false;
errorMessage = '';
ngOnInit() {
this.loadPosts();
}
loadPosts() {
this.isLoading = true;
this.postService.getPosts(this.page, this.limit).subscribe({
next: (data) => {
this.posts = [...this.posts, ...data]; // Append new data
this.page++; // Increase page count
this.isLoading = false;
},
error: (error) => {
this.errorMessage = error.message;
this.isLoading = false;
}
});
36/411
}
}
html
<div class="container">
<h2>Blog Posts</h2>
<ul>
<li *ngFor="let post of posts">
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
</li>
</ul>
css
.container {
max-width: 600px;
margin: auto;
text-align: center;
}
ul {
list-style: none;
padding: 0;
}
37/411
li {
border-bottom: 1px solid #ddd;
padding: 10px 0;
}
button {
padding: 8px 16px;
background: #007bff;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background: #0056b3;
}
.error {
color: red;
}
How It Works
✅ Initially, 2 posts are loaded.
✅ Clicking "Load More" fetches 2 more posts.
✅ If an error occurs, a message is displayed.
✅ If all posts are loaded, the button disappears.
Summary
Feature Implementation
38/411
Feature Implementation
This is a real-world Angular project structure for handling API data, pagination, and error
management. 🚀
Would you like to add filtering or search functionality next? 🔍
Adding Filtering and Search Functionality in Angular
We will enhance our existing blog post list by adding:
✅ Search functionality (Filter posts by title)
✅ Category filtering (Filter posts based on categories)
json
{
"posts": [
{ "id": 1, "title": "Angular Basics", "content": "Learn Angular step by step",
"category": "Angular" },
{ "id": 2, "title": "RxJS in Angular", "content": "Understanding Observables",
"category": "RxJS" },
{ "id": 3, "title": "HttpClient Usage", "content": "Making API calls in Angular",
"category": "Angular" },
{ "id": 4, "title": "Pagination in Angular", "content": "Implementing load more
functionality", "category": "UI/UX" },
{ "id": 5, "title": "State Management in Angular", "content": "Using NgRx effectively",
"category": "NgRx" }
]
}
sh
39/411
Step 2: Update the Post Service
Modify post.service.ts to support search and category filtering.
typescript
@Injectable({
providedIn: 'root'
})
export class PostService {
private apiUrl = 'http://localhost:3000/posts';
if (search) {
url += `&title_like=${search}`; // JSON Server supports "title_like" for filtering
}
if (category) {
url += `&category=${category}`;
}
return this.http.get(url).pipe(
retry(2),
catchError(this.handleError)
);
}
40/411
Step 3: Update the Component
Modify app.component.ts to handle search & category selection.
typescript
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
posts: any[] = [];
page = 1;
limit = 2;
searchText = '';
selectedCategory = '';
isLoading = false;
errorMessage = '';
categories = ['All', 'Angular', 'RxJS', 'UI/UX', 'NgRx']; // Available categories
ngOnInit() {
this.loadPosts();
}
loadPosts() {
this.isLoading = true;
const category = this.selectedCategory === 'All' ? '' : this.selectedCategory;
41/411
onSearch() {
this.page = 1;
this.posts = [];
this.loadPosts();
}
onCategoryChange() {
this.page = 1;
this.posts = [];
this.loadPosts();
}
}
<div class="container">
<h2>Blog Posts</h2>
42/411
<p *ngIf="errorMessage" class="error">{{ errorMessage }}</p>
css
.container {
max-width: 600px;
margin: auto;
text-align: center;
}
input, select {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
ul {
list-style: none;
padding: 0;
}
li {
border-bottom: 1px solid #ddd;
padding: 10px 0;
}
button {
padding: 8px 16px;
background: #007bff;
color: white;
border: none;
cursor: pointer;
43/411
}
button:hover {
background: #0056b3;
}
.error {
color: red;
}
How It Works
✅ Search input: Filters posts as the user types.
✅ Category filter: Shows only posts from the selected category.
✅ Pagination: Click Load More to fetch more posts.
✅ Error handling: If something goes wrong, a message appears.
Summary
Feature Implementation
🚀 Next Steps
Would you like to: 1️⃣ Add sorting (e.g., latest posts first)?
2️⃣ Implement infinite scrolling instead of a Load More button?
Enhancing Blog Post List with Sorting and Infinite Scroll
44/411
We'll now add:
✅ Sorting functionality (Sort posts by newest first)
✅ Infinite scrolling (Auto-load posts when the user scrolls)
typescript
getPosts(page: number, limit: number, search: string = '', category: string = '', sortBy:
string = 'id', order: string = 'desc'): Observable<any> {
let url = `${this.apiUrl}?_page=${page}&_limit=${limit}&_sort=${sortBy}&_order=${order}`;
if (search) {
url += `&title_like=${search}`;
}
if (category) {
url += `&category=${category}`;
}
return this.http.get(url).pipe(
retry(2),
catchError(this.handleError)
);
}
typescript
@Component({
selector: 'app-root',
45/411
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
posts: any[] = [];
page = 1;
limit = 2;
searchText = '';
selectedCategory = '';
selectedSort = 'id';
isLoading = false;
errorMessage = '';
categories = ['All', 'Angular', 'RxJS', 'UI/UX', 'NgRx'];
sortOptions = [{ label: 'Newest First', value: 'id' }, { label: 'Title (A-Z)', value:
'title' }];
ngOnInit() {
this.loadPosts();
}
loadPosts() {
if (this.isLoading) return;
this.isLoading = true;
const category = this.selectedCategory === 'All' ? '' : this.selectedCategory;
onSearch() {
this.resetPosts();
}
46/411
onCategoryChange() {
this.resetPosts();
}
onSortChange() {
this.resetPosts();
}
resetPosts() {
this.page = 1;
this.posts = [];
this.loadPosts();
}
@HostListener('window:scroll', [])
onScroll(): void {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
this.loadPosts();
}
}
}
html
<div class="container">
<h2>Blog Posts</h2>
<ul>
47/411
<li *ngFor="let post of posts">
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
<small><b>Category:</b> {{ post.category }}</small>
</li>
</ul>
How It Works
✅ Sorting: Select sort order from dropdown.
✅ Infinite Scrolling: Loads more posts when scrolling down.
🚀 Next Steps
Would you like to: 1️⃣ Add a "Back to Top" button?
2️⃣ Implement a skeleton loader for smooth UX?
Enhancing UX with "Back to Top" Button & Skeleton Loader
We'll now add:
✅ "Back to Top" button (Smoothly scrolls to the top)
✅ Skeleton Loader (Shows a placeholder while loading)
typescript
@Component({
48/411
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
posts: any[] = [];
page = 1;
limit = 2;
searchText = '';
selectedCategory = '';
selectedSort = 'id';
isLoading = false;
errorMessage = '';
categories = ['All', 'Angular', 'RxJS', 'UI/UX', 'NgRx'];
sortOptions = [{ label: 'Newest First', value: 'id' }, { label: 'Title (A-Z)', value:
'title' }];
showBackToTop = false; // Controls visibility of the button
ngOnInit() {
this.loadPosts();
}
loadPosts() {
if (this.isLoading) return;
this.isLoading = true;
const category = this.selectedCategory === 'All' ? '' : this.selectedCategory;
onSearch() {
this.resetPosts();
49/411
}
onCategoryChange() {
this.resetPosts();
}
onSortChange() {
this.resetPosts();
}
resetPosts() {
this.page = 1;
this.posts = [];
this.loadPosts();
}
@HostListener('window:scroll', [])
onScroll(): void {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
this.loadPosts();
}
this.showBackToTop = window.scrollY > 300;
}
scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
}
html
<div class="container">
<h2>Blog Posts</h2>
50/411
<select [(ngModel)]="selectedSort" (change)="onSortChange()">
<option *ngFor="let option of sortOptions" [value]="option.value">{{ option.label }}
</option>
</select>
<ul>
<li *ngFor="let post of posts">
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
<small><b>Category:</b> {{ post.category }}</small>
</li>
<p *ngIf="isLoading">Loading...</p>
</div>
css
.container {
max-width: 600px;
margin: auto;
text-align: center;
}
input, select {
width: 100%;
51/411
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
ul {
list-style: none;
padding: 0;
}
li {
border-bottom: 1px solid #ddd;
padding: 10px 0;
}
button {
padding: 8px 16px;
background: #007bff;
color: white;
border: none;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background: #0056b3;
}
/* Skeleton Loader */
.skeleton {
background: #ddd;
border-radius: 5px;
animation: shimmer 1.5s infinite;
}
.skeleton-title {
height: 20px;
width: 80%;
margin: 10px auto;
}
.skeleton-text {
height: 15px;
width: 90%;
margin: 5px auto;
52/411
}
@keyframes shimmer {
0% { background: #eee; }
50% { background: #ddd; }
100% { background: #eee; }
}
.back-to-top:hover {
background: #218838;
}
How It Works
✅ Back to Top Button: Appears when scrolled 300px down.
✅ Smooth Scroll: Clicking the button smoothly scrolls to the top.
✅ Skeleton Loader: Shows placeholders while posts are loading.
🚀 Next Steps
Would you like to: 1️⃣ Add animations when new posts load?
2️⃣ Show a toast notification on error or success?
Enhancing UX with Animations & Toast Notifications
We'll now add:
✅ Fade-in animation for newly loaded posts
✅ Toast notifications for success & error messages
53/411
Step 1: Add Animations for Post Loading
Modify app.component.ts :
typescript
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
animations: [
trigger('fadeIn', [
transition(':enter', [
style({ opacity: 0, transform: 'translateY(10px)' }),
animate('500ms ease-out', style({ opacity: 1, transform: 'translateY(0)' }))
])
])
]
})
export class AppComponent implements OnInit {
posts: any[] = [];
page = 1;
limit = 2;
searchText = '';
selectedCategory = '';
selectedSort = 'id';
isLoading = false;
errorMessage = '';
showBackToTop = false;
showToast = false;
toastMessage = '';
toastType = 'success';
ngOnInit() {
this.loadPosts();
}
loadPosts() {
if (this.isLoading) return;
this.isLoading = true;
54/411
const category = this.selectedCategory === 'All' ? '' : this.selectedCategory;
onSearch() {
this.resetPosts();
}
onCategoryChange() {
this.resetPosts();
}
onSortChange() {
this.resetPosts();
}
resetPosts() {
this.page = 1;
this.posts = [];
this.loadPosts();
}
@HostListener('window:scroll', [])
onScroll(): void {
if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 100) {
this.loadPosts();
}
this.showBackToTop = window.scrollY > 300;
}
scrollToTop() {
window.scrollTo({ top: 0, behavior: 'smooth' });
55/411
}
setTimeout(() => {
this.showToast = false;
}, 3000);
}
}
html
<div class="container">
<h2>Blog Posts</h2>
<ul>
<li *ngFor="let post of posts" @fadeIn>
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
<small><b>Category:</b> {{ post.category }}</small>
</li>
56/411
<div class="skeleton skeleton-title"></div>
<div class="skeleton skeleton-text"></div>
</li>
</ul>
<p *ngIf="isLoading">Loading...</p>
</div>
css
.container {
max-width: 600px;
margin: auto;
text-align: center;
}
input, select {
width: 100%;
padding: 8px;
margin-bottom: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
ul {
list-style: none;
padding: 0;
}
57/411
li {
border-bottom: 1px solid #ddd;
padding: 10px 0;
}
/* Skeleton Loader */
.skeleton {
background: #ddd;
border-radius: 5px;
animation: shimmer 1.5s infinite;
}
.skeleton-title {
height: 20px;
width: 80%;
margin: 10px auto;
}
.skeleton-text {
height: 15px;
width: 90%;
margin: 5px auto;
}
@keyframes shimmer {
0% { background: #eee; }
50% { background: #ddd; }
100% { background: #eee; }
}
.back-to-top:hover {
background: #218838;
}
58/411
/* Toast Notification */
.toast {
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
padding: 10px 20px;
color: white;
border-radius: 5px;
font-weight: bold;
animation: fadeInOut 3s ease-in-out;
}
.toast.success {
background: #28a745;
}
.toast.error {
background: #dc3545;
}
@keyframes fadeInOut {
0% { opacity: 0; transform: translateY(10px); }
20% { opacity: 1; transform: translateY(0); }
80% { opacity: 1; }
100% { opacity: 0; transform: translateY(-10px); }
}
How It Works
✅ Fade-in Animation: Posts smoothly appear when loaded.
✅ Toast Notifications: Shows a success or error message for 3 seconds.
🚀 Next Steps
Would you like to:
1️⃣ Add a dark mode toggle?
2️⃣ Enhance the toast notifications with icons?
59/411
What is the difference between let and var keyword ?
03:03
Q58. What is Type annotation ?
01:28
Q59.What are Built in/Primitive & UserDefined/Non-primitive types
in Typescript?
01:53
Q61. What is Enum type in Typescript ?
02:11
Q62. What is the difference between void and never types in
Typescript ?
01:32
Q63. What is Type Assertion in Typescript ?
01:57
Q64. What are Arrow Functions in Typescript ?
var (Function-scoped)
let (Block-scoped)
Variables are hoisted but not initialized (throws an error if accessed before declaration).
Example:
typescript
function testVarLet() {
if (true) {
var a = 10; // Function-scoped
let b = 20; // Block-scoped
}
console.log(a); // ✅ Works (because `var` is function-scoped)
console.log(b); // ❌ Error (because `let` is block-scoped)
60/411
}
testVarLet();
Example:
typescript
string
number
boolean
null
undefined
bigint
symbol
Example:
typescript
61/411
let isDone: boolean = true;
let score: number = 95;
let message: string = "Hello!";
These include:
arrays
objects
tuples
enums
functions
classes
interfaces
Example:
typescript
typescript
enum Status {
Pending, // 0
InProgress, // 1
Completed // 2
}
console.log(Status.InProgress); // Output: 1
typescript
62/411
enum Direction {
Up = "UP",
Down = "DOWN"
}
console.log(Direction.Up); // Output: "UP"
Q62: What is the difference between void and never types in TypeScript?
Feature void never
Usage Used when a function does not Used for functions that never return (throw
return a value error or infinite loop)
Example
```typescript
function logMessage():
void {
console.log("Logging...");
| ```typescript
function throwError(): never {
throw new Error("This will never return");
}
``` |
---
63/411
typescript
Example:
typescript
Key Features:
✅ Concise syntax
✅ No binding (uses parent scope’s
this this )
typescript
class Person {
name = "Alice";
sayHello = () => {
console.log("Hello, " + this.name);
};
}
const p = new Person();
p.sayHello(); // Output: Hello, Alice
64/411
OOP Concepts in TypeScript
1. Classes and Objects
2. Encapsulation
3. Inheritance
4. Polymorphism
5. Abstraction
What is an Object?
An object is an instance of a class. It contains values for the properties defined in the class.
Example:
typescript
class Person {
name: string;
age: number;
greet(): void {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// Creating an object
65/411
let person1 = new Person("John", 30);
person1.greet(); // Output: Hello, my name is John and I am 30 years old.
2. Encapsulation
Encapsulation is the process of restricting direct access to class properties and methods to protect
data.
Example of Encapsulation:
typescript
class BankAccount {
private balance: number = 0;
getBalance(): number {
return this.balance;
}
}
66/411
3. Inheritance
Inheritance allows a class to inherit properties and methods from another class, promoting code
reusability.
Example of Inheritance:
typescript
class Animal {
constructor(public name: string) {}
makeSound(): void {
console.log("Some sound...");
}
}
4. Polymorphism
Polymorphism allows a subclass to override a method of its superclass, providing different
implementations.
Example of Polymorphism:
typescript
class Shape {
area(): void {
console.log("Calculating area...");
}
}
67/411
class Circle extends Shape {
radius: number;
constructor(radius: number) {
super();
this.radius = radius;
}
area(): void {
console.log(`Circle Area: ${Math.PI * this.radius * this.radius}`);
}
}
5. Abstraction
Abstraction hides implementation details and only exposes necessary functionalities.
Example of Abstraction:
typescript
start(): void {
console.log("Vehicle is starting...");
}
}
68/411
}
Conclusion
TypeScript’s Object-Oriented Programming (OOP) features enhance code organization, reusability,
and maintainability. The key OOP principles include:
Classes:
69/411
A class is a blueprint for creating objects.
It defines properties (variables) and methods (functions) that objects will have.
Objects:
Example:
typescript
class Person {
name: string;
age: number;
greet(): void {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
Example:
typescript
class Car {
model: string;
constructor(model: string) {
70/411
this.model = model;
}
showModel(): void {
console.log(`Car Model: ${this.model}`);
}
}
Modifier Description
Example:
typescript
class BankAccount {
private balance: number;
constructor(balance: number) {
this.balance = balance;
}
getBalance(): number {
return this.balance; // ✅ Allowed
}
}
71/411
Q69: What is Encapsulation in TypeScript?
Encapsulation is the concept of hiding data and allowing controlled access using methods.
Example:
typescript
class Employee {
private salary: number;
constructor(salary: number) {
this.salary = salary;
}
getSalary(): number {
return this.salary; // Controlled access
}
}
Example:
typescript
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): void {
72/411
console.log("Some sound...");
}
}
Example:
typescript
class Shape {
area(): void {
console.log("Calculating area...");
}
}
constructor(radius: number) {
super();
this.radius = radius;
}
73/411
let myCircle = new Circle(5);
myCircle.area(); // Output: Circle Area: 78.54
Used for defining properties and methods but does not contain implementation.
Example:
typescript
interface IAnimal {
name: string;
makeSound(): void;
}
constructor(name: string) {
this.name = name;
}
makeSound(): void {
console.log(`${this.name} says Woof!`);
}
}
74/411
Feature extends implements
typescript
class Parent {
greet(): void {
console.log("Hello from Parent class!");
}
}
typescript
interface Printable {
print(): void;
}
75/411
No, TypeScript does not support multiple inheritance (i.e., a class cannot extend multiple classes).
class A {}
class B {}
class C extends A, B {} // ❌ Error: Multiple inheritance is not allowed
Solution: Use Interfaces for Multiple Inheritance
While multiple inheritance is not allowed, you can implement multiple interfaces.
interface Flyable {
fly(): void;
}
interface Swimmable {
swim(): void;
}
swim(): void {
console.log("Bird is swimming!");
}
}
Conclusion
✅ Classes & Objects - Define blueprints and create instances
✅ Constructor - Initializes an object’s properties
76/411
✅ Access Modifiers - public , private, protected
✅ Encapsulation - Hides data and allows controlled access
✅ Inheritance - Allows code reuse between classes
✅ Polymorphism - Enables method overriding
✅ Interfaces - Define contracts for classes
✅ Extends vs Implements - Inheritance vs interface implementation
✅ Multiple Inheritance - Not supported, but multiple interfaces can be implemented
Would you like further clarifications or examples? 🚀
typescript
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule], // Import FormsModule
bootstrap: [AppComponent]
})
export class AppModule {}
77/411
html
<button type="submit">Submit</button>
</form>
typescript
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
onSubmit(form: any) {
console.log("Form Submitted:", form.value);
}
}
✅ Now, the form is ready, and values will be logged when submitted.
html
<form #userForm="ngForm">
<label for="email">Email:</label>
<input type="email" id="email" name="email" ngModel required #emailField="ngModel">
78/411
<button [disabled]="userForm.invalid">Submit</button>
</form>
Example:
typescript
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
userForm = new FormGroup({
name: new FormControl(''),
email: new FormControl('')
});
onSubmit() {
console.log(this.userForm.value);
}
}
typescript
79/411
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [ReactiveFormsModule]
})
export class AppModule {}
typescript
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
userForm = new FormGroup({
name: new FormControl(''),
email: new FormControl('')
});
onSubmit() {
console.log(this.userForm.value);
}
}
html
<label for="email">Email:</label>
<input id="email" formControlName="email">
<button type="submit">Submit</button>
</form>
✅ Now, the form is bound to userForm and submits data via the component.
80/411
Q81: How to do Validations in Reactive Forms?
Use Angular’s Validators to add validation rules.
<label>Email:</label>
<input formControlName="email">
<div *ngIf="userForm.get('email')?.invalid && userForm.get('email')?.touched">
<p *ngIf="userForm.get('email')?.errors?.required">Email is required.</p>
<p *ngIf="userForm.get('email')?.errors?.email">Invalid email format.</p>
</div>
<button [disabled]="userForm.invalid">Submit</button>
</form>
81/411
Comparison: Template-Driven vs. Reactive Forms
Feature Template-Driven Forms Reactive Forms
Use Case Simple forms Complex forms (dynamic forms, custom validators)
Summary
✅ Template-Driven Forms - Uses , simpler, HTML-driven.
ngModel
✅ Reactive Forms - Uses FormGroup , FormControl , and for better control.
Validators
✅ Validations - Apply required fields and validation messages using Angular’s built-in features.
Would you like more examples or explanations? 🚀
82/411
🔹 Step 1: Create an Authentication Service ( auth.service.ts )
typescript
@Injectable({
providedIn: 'root'
})
export class AuthService {
private baseUrl = 'https://your-api-url.com/auth'; // Backend API URL
// Retrieve Token
getToken(): string | null {
return localStorage.getItem('token');
}
// Logout
logout() {
localStorage.removeItem('token');
}
83/411
🔹 Step 2: Implement Login Component ( login.component.ts )
typescript
@Component({
selector: 'app-login',
templateUrl: './login.component.html'
})
export class LoginComponent {
email = '';
password = '';
login() {
this.authService.login({ email: this.email, password: this.password }).subscribe(
(response) => {
this.authService.storeToken(response.token); // Store token in local storage
this.router.navigate(['/dashboard']); // Redirect to dashboard
},
(error) => {
console.error('Login failed:', error);
}
);
}
}
html
<form (ngSubmit)="login()">
<label>Email:</label>
<input type="email" [(ngModel)]="email" name="email" required />
<label>Password:</label>
<input type="password" [(ngModel)]="password" name="password" required />
84/411
<button type="submit">Login</button>
</form>
typescript
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (this.authService.isAuthenticated()) {
return true;
} else {
this.router.navigate(['/login']); // Redirect to login if not authenticated
return false;
}
}
}
typescript
85/411
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] }, // Protected
Route
{ path: 'login', component: LoginComponent }, // Public Route
{ path: '', redirectTo: '/login', pathMatch: 'full' } // Default Route
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
typescript
storeUserRole(role: string) {
localStorage.setItem('userRole', role);
}
86/411
🔹 Step 7: Create a Role-Based Guard ( role.guard.ts )
typescript
@Injectable({
providedIn: 'root'
})
export class RoleGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
const role = this.authService.getUserRole();
if (role === 'admin') {
return true;
} else {
this.router.navigate(['/access-denied']); // Redirect unauthorized users
return false;
}
}
}
Authentication:
Users must log in with their credentials before accessing their bank accounts.
Authorization:
Regular users can only view account details & transfer money.
4️⃣ Summary
🔹 Authentication → Verifies who the user is (Login System).
🔹 Authorization → Controls what the user can do (Role-Based Access).
🔹 Angular Guards → Protect routes using authentication and roles.
🔹 JWT Token → Used to store login sessions securely.
🚀 Would you like help with backend integration for JWT?
JWT Authentication with Angular and Java Spring Boot Backend
Now, let’s integrate JWT authentication with a Java Spring Boot backend to handle user authentication.
xml
88/411
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String role;
89/411
// Getters & Setters
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
}
import io.jsonwebtoken.*;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
public class JwtUtil {
private String secretKey = "your_secret_key"; // Change this for production
90/411
.getSubject();
}
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.Optional;
@Service
public class AuthService {
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final JwtUtil jwtUtil;
91/411
}
throw new RuntimeException("Invalid username or password");
}
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/auth")
public class AuthController {
private final AuthService authService;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest request) {
String token = authService.login(request.getUsername(), request.getPassword());
return ResponseEntity.ok(new AuthResponse(token));
}
@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody User user) {
authService.register(user);
return ResponseEntity.ok("User registered successfully");
}
}
92/411
🔹 Step 7: Create Security Configuration
java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
93/411
typescript
@NgModule({
imports: [HttpClientModule]
})
export class AppModule { }
typescript
@Injectable({
providedIn: 'root'
})
export class AuthService {
private apiUrl = 'http://localhost:8080/auth';
storeToken(token: string) {
localStorage.setItem('token', token);
}
logout() {
localStorage.removeItem('token');
94/411
}
}
typescript
@Component({
selector: 'app-login',
templateUrl: './login.component.html'
})
export class LoginComponent {
username = '';
password = '';
login() {
this.authService.login({ username: this.username, password: this.password }).subscribe(
(response) => {
this.authService.storeToken(response.token);
this.router.navigate(['/dashboard']);
},
(error) => {
console.error('Login failed:', error);
}
);
}
}
✅ Summary
1. Spring Boot Backend
95/411
Secures endpoints with Spring Security.
2. Angular Frontend
🔹 Using json-server
1. Install json-server
sh
96/411
2. Create db.json
json
{
"users": [
{ "id": 1, "username": "admin", "password": "12345", "token": "mock-jwt-token" }
]
}
sh
typescript
@Injectable({
providedIn: 'root'
})
export class AuthService {
private apiUrl = 'http://localhost:3000';
97/411
storeToken(token: string) {
localStorage.setItem('token', token);
}
logout() {
localStorage.removeItem('token');
}
}
🔹 Create auth.guard.ts
typescript
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(): boolean {
if (this.authService.getToken()) {
return true;
} else {
this.router.navigate(['/login']);
return false;
}
}
}
98/411
typescript
🔹 Create auth.interceptor.ts
typescript
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const token = localStorage.getItem('token');
if (token) {
req = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
}
return next.handle(req);
}
}
🔹 Register in app.module.ts
typescript
@NgModule({
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
]
})
export class AppModule { }
99/411
Q88: How to Retry Automatically on API Error?
Use retry() from RxJS.
typescript
this.http.get('api/data')
.pipe(
retry(3),
catchError(error => throwError(() => error))
)
.subscribe();
Example JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.dGVzdFNpZ25hdHVyZQ
100/411
Q91: Where is the JWT Token Stored in a Request?
✅ Stored in the Authorization Header
http
✅ Summary
✔ Mock API using json-server
✔ Implement JWT authentication in Angular
✔ Use Auth Guards to protect routes
✔ Use Interceptors to attach tokens
✔ Retry API calls on failure
101/411
Q93: What is Content Projection? What is <ng-content> ?
✅ Content Projection allows inserting external HTML into a component dynamically.
✅ <ng-content>acts as a placeholder for projected content.
Example:
html
<app-card>
<h2>Title from Parent</h2>
<p>Content from Parent</p>
</app-card>
html
<div class="card">
<ng-content></ng-content>
</div>
📌 Output
html
<div class="card">
<h2>Title from Parent</h2>
<p>Content from Parent</p>
</div>
Example:
html
typescript
102/411
logValue(value: string) {
console.log(value);
}
typescript
typescript
@Component({
selector: 'app-parent',
template: `<app-child></app-child> <button (click)="showMessage()">Get Child
Message</button>`
})
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) child!: ChildComponent;
ngAfterViewInit() {
console.log(this.child.message);
}
showMessage() {
alert(this.child.message);
103/411
}
}
typescript
ngAfterViewInit() {
this.children.forEach(child => console.log(child.message));
}
Example:
104/411
html
<app-container>
<h2 #title>Projected Title</h2>
</app-container>
typescript
ngAfterContentInit() {
console.log(this.title.nativeElement.innerText);
}
Purpose Project Access single child Access Access single Access multiple
external component multiple child projected element projected
content components elements
105/411
<ng-
Feature content> ViewChild ViewChildren ContentChild ContentChildren
✅ Summary
✔ Content Projection → <ng-content>
✔ ViewChild → Access child component or DOM element
✔ ViewChildren → Access multiple child components
✔ ContentChild → Access single projected content
✔ ContentChildren → Access multiple projected contents
typescript
@Component({
selector: 'app-child',
template: `<p>Child Component - Message: {{ message }}</p>`,
styles: [`p { color: blue; font-weight: bold; }`]
})
export class ChildComponent {
@Input() message: string = 'Default Message';
}
106/411
Step 2: Create a Parent Component ( parent.component.ts )
Uses @ViewChild to access a single child component.
typescript
import {
Component, ViewChild, ViewChildren, ContentChild, ContentChildren, QueryList, ElementRef,
AfterViewInit
} from '@angular/core';
import { ChildComponent } from './child.component';
@Component({
selector: 'app-parent',
template: `
<h2>Parent Component</h2>
107/411
// ContentChild - Access single projected content
@ContentChild('projectedContent') projectedElement!: ElementRef;
ngAfterViewInit() {
console.log('ViewChild Message:', this.singleChild.message);
console.log('ViewChildren Messages:', this.multipleChildren.map(child => child.message));
}
showDetails() {
console.log('Projected Content:', this.projectedElement.nativeElement.innerText);
console.log('Projected Children Messages:', this.projectedChildren.map(child =>
child.message));
}
}
typescript
@Component({
selector: 'app-container',
template: `
<div class="container">
<h3>Container Component</h3>
<ng-content></ng-content>
</div>
`,
styles: [`.container { border: 1px solid black; padding: 10px; margin-top: 10px; }`]
})
export class ContainerComponent implements AfterContentInit {
// ContentChild - Access projected single element
@ContentChild('projectedContent') projectedElement!: ElementRef;
108/411
@ContentChildren(ChildComponent) projectedChildren!: QueryList<ChildComponent>;
ngAfterContentInit() {
console.log('ContentChild (Projected Content):',
this.projectedElement.nativeElement.innerText);
console.log('ContentChildren (Projected Child Components):',
this.projectedChildren.map(child => child.message));
}
}
🎯 Expected Output
1. ViewChild: Access single child component.
📌 Summary
Feature Access Scope Use Case Example
🚀 Now, your Angular project efficiently uses Content Projection & Component Queries!
Would you like more details or modifications? 😊
109/411
DOM?
02:31
Q6. What are selectors in JS?
01:05
Q7. Difference getElementById, getElementsByClassName and get
elementsByTagName?
02:42
Q8. What are data types in JS?
js
2. Accessing Characters
js
console.log(str[0]); // 'H'
console.log(str.charAt(1)); // 'e'
3. Substring Extraction
slice(start, end)
substring(start, end)
substr(start, length)
js
4. String Search
indexOf()
lastIndexOf()
includes()
js
console.log(str.indexOf("World")); // 7
console.log(str.lastIndexOf("o")); // 8
110/411
console.log(str.includes("Hello")); // true
5. String Replacement
replace()
replaceAll()
js
6. String Conversion
toUpperCase()
toLowerCase()
js
7. String Concatenation
concat()
js
8. Trimming Strings
trim()
trimStart()
trimEnd()
js
9. Splitting Strings
split()
js
111/411
console.log(str.split(",")); // ['Hello', ' World!']
Definition Markup language defining webpage structure Programming interface for web documents
Selectors in JavaScript
Selectors are methods to find elements in the DOM.
1. ID Selector – document.getElementById("id")
Access
Method Returns Type Example
112/411
Access
Method Returns Type Example
String
Number
Boolean
BigInt
Symbol
Undefined
Null
js
Object
Array
Function
js
113/411
Would you like examples on any specific topic? 🚀
What are operators in JS and their different types?
1. Arithmetic Operators
These operators are used for mathematical calculations.
+ Addition 5 + 2 // 7
- Subtraction 5 - 2 // 3
* Multiplication 5 * 2 // 10
/ Division 5 / 2 // 2.5
% Modulus (Remainder) 5 % 2 // 1
2. Assignment Operators
These operators assign values to variables.
= Assigns value x = 10
114/411
3. Comparison Operators
These operators compare values and return true or false .
4. Logical Operators
Used to combine multiple conditions.
` `
5. Bitwise Operators
These operators work on binary numbers.
` ` OR
^ XOR 5 ^ 1 // 4
~ NOT ~5 // -6
115/411
6. Ternary Operator
A shortcut for if-else conditions.
js
7. Type Operators
Used to determine data types.
js
116/411
02:14
Q14. What are Arrays in JS? How to get, add & remove elements
from arrays?
02:59
Q15. What are Objects in JS?
02:00
Q16. What is Scope in JavaScript?
01:24
Q17. What is Hoisting in JavaScript?
01:49
Q18. What is Error Handling in JS?
01:16
Q19. What is JSON?
01:00
Q20. What is asynchronous programming in JS? What is its use?
Conditional statements are used to execute different blocks of code based on conditions.
1. if Statement
js
2. if-else Statement
js
3. else-if Ladder
js
117/411
console.log("A Grade");
} else if (marks >= 75) {
console.log("B Grade");
} else {
console.log("C Grade");
}
4. Ternary Operator
js
5. Switch Case
js
Types of Loops:
1. for Loop
js
118/411
2. while Loop
js
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
3. do-while Loop
js
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
js
Q12. What are Functions in JavaScript? What are the types of functions?
Types of Functions:
1. Named Function
js
function greet() {
return "Hello!";
}
console.log(greet());
2. Anonymous Function
js
119/411
let greet = function() {
return "Hello!";
};
console.log(greet());
3. Arrow Function
js
js
(function() {
console.log("I am an IIFE!");
})();
Arrow functions provide a shorter syntax for writing functions and do not bind their own this .
js
Uses:
Shorter syntax
Q14. What are Arrays in JavaScript? How to get, add & remove elements from arrays?
js
120/411
let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Access an element
Adding Elements:
js
Removing Elements:
js
js
let person = {
name: "John",
age: 25,
greet: function() {
return "Hello!";
}
};
console.log(person.name); // John
console.log(person.greet()); // Hello!
js
121/411
let globalVar = "I am global";
js
function test() {
let localVar = "I am local";
}
js
if (true) {
let blockVar = "I am block-scoped";
}
Hoisting moves function and variable declarations to the top of their scope.
js
js
greet(); // Works!
function greet() {
console.log("Hello!");
}
js
122/411
try {
let x = undefinedVariable; // Throws error
} catch (error) {
console.log("Error caught:", error.message);
} finally {
console.log("This runs always.");
}
js
js
console.log("Start");
setTimeout(() => console.log("Async Task"), 2000);
console.log("End");
Uses:
Improves performance
123/411
Let me know if you need more details on any topic! 🚀
What are variables? What is the difference between var, let, and
const ?
03:32
Q22. What are data types in JS?
01:23
Q23. What is the difference between primitive and non-primitive
data types?
04:07
Q24. What is the difference between null and undefined in JS?
02:22
Q25. What is the use of typeof operator?
01:16
Q26. What is type coercion in JS?
Q21. What are variables? What is the difference between var , let , and const ?
js
var x = 10;
let y = 20;
const z = 30;
Differences:
Hoisting Hoisted with undefined Hoisted without value Hoisted without value
Example:
js
124/411
Q22. What are data types in JavaScript?
String → "Hello"
Number → 42
Null → null
Undefined → undefined
Symbol → Symbol('id')
BigInt → 9007199254740991n
Object
Array
Function
Q23. What is the difference between primitive and non-primitive data types?
Example:
js
125/411
obj2.name = "Bob";
console.log(obj1.name); // "Bob" (changes because of reference)
Meaning Empty or intentional absence of value Variable declared but not assigned
Example:
js
let a;
console.log(a); // undefined
let b = null;
console.log(b); // null
js
126/411
Type coercion automatically converts values between types.
js
js
console.log(Number("42")); // 42
console.log(String(42)); // "42"
console.log(Boolean(0)); // false
console.log(Boolean(1)); // true
JavaScript Operators
127/411
Q27. What are operators? What are the types of operators in JavaScript?
js
console.log(5 + 3); // 8
console.log(10 % 3); // 1 (remainder)
console.log(2 ** 3); // 8 (exponentiation)
js
js
js
let x = 10;
x += 5; // x = x + 5
console.log(x); // 15
js
js
128/411
console.log(status); // "Adult"
js
Q28. What is the difference between unary, binary, and ternary operators?
🔹 Examples:
js
// Unary
let a = 10;
console.log(-a); // -10
// Binary
let b = 5 + 3;
console.log(b); // 8
// Ternary
let age = 18;
let message = age >= 18 ? "Adult" : "Minor";
console.log(message); // "Adult"
129/411
Short-circuiting means stopping evaluation once the result is determined.
js
js
2. ** – Exponentiation
4. + , - – Addition, Subtraction
8. || – Logical OR
9. =, +=, -= – Assignment
🔹 Example:
js
130/411
Conditional Statements in JavaScript
1. if Statement
js
2. if-else Statement
js
js
4. Switch Statement
js
131/411
break;
default:
console.log("Regular day");
}
if Simple conditions
132/411
Operator Type Example Result
🔹 Example:
js
Q34. What is the difference between Spread and Rest operators in JavaScript?
js
js
function sum(...nums) {
return nums.reduce((acc, val) => acc + val, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
133/411
Q37. What is the difference between find() and filter() methods of
an Array?
03:02
Q38. What is the slice() method of an Array?
01:16
Q39. What is the difference between push() and concat () methods
of an Array ?
01:27
Q40. What is the difference between pop() and shift() methods of
an Array?
01:22
Q41. What is the splice() method of an Array?
03:27
Q42. Difference between the slice() and splice() methods of an
Array?
00:40
Q43. What is the difference map() and for Each() array methods of
an Array?
02:37
Q44. How to sort and reverse an array?
00:51
Q45. What is Array Destructuring in JS?
01:38
Q46. What are array-like objects In JS?
02:52
Q47. How to convert an array-like object into an array?
🔹 Creating an Array
js
js
134/411
console.log(fruits[0]); // "Apple"
console.log(fruits[1]); // "Banana"
console.log(fruits[fruits.length - 1]); // "Cherry"
Using forEach()
js
js
fruits.push("Mango");
console.log(fruits); // ["Apple", "Banana", "Cherry", "Mango"]
js
fruits.unshift("Grapes");
console.log(fruits); // ["Grapes", "Apple", "Banana", "Cherry", "Mango"]
js
fruits.pop();
console.log(fruits); // ["Grapes", "Apple", "Banana", "Cherry"]
js
135/411
fruits.shift();
console.log(fruits); // ["Apple", "Banana", "Cherry"]
js
js
js
136/411
let arr = ["A", "B", "C", "D", "E"];
console.log(arr.slice(1, 4)); // ["B", "C", "D"]
console.log(arr); // ["A", "B", "C", "D", "E"] (Original unchanged)
arr1.push(6);
console.log(arr1); // [1, 2, 3, 6]
console.log(items.pop()); // "Eraser"
console.log(items.shift()); // "Pen"
console.log(items); // ["Book"]
137/411
Q41. What is the splice() method of an Array?
Modifies an array by adding/removing elements.
js
js
138/411
let nums = [1, 2, 3];
js
Reverse ( reverse() )
js
fruits.reverse();
console.log(fruits); // ["Mango", "Banana", "Apple"]
js
139/411
Objects that look like arrays but lack array methods.
js
function showArgs() {
console.log(arguments[0]); // "Hello"
}
showArgs("Hello", "World");
js
function convertToArray() {
let arr = Array.from(arguments);
console.log(arr);
}
convertToArray(1, 2, 3); // [1, 2, 3]
🚀 That’s a complete overview of JavaScript Arrays & Methods! Let me know if you need more details!
😊
What is a loop? What are the types of loops in JS?
01:25
Q49. What is the difference between while and for loops?
02:13
Q50. What is the difference between while and do-while loops?
01:50
Q51. What is the difference between break and continue
statement?
01:35
Q52. What is the difference between for and for…of loop in JS?
01:32
Q53. What is the difference between for…of and for…in loop?
01:28
Q54. What is forEach method? Compare it with for…of and for…in
140/411
loop?
02:32
Q55. When to use for…of loop and when to use forEach method in
applications?
3. do...while loop – Executes at least once, then repeats while a condition is true.
5. for...of loop – Iterates over iterable objects like arrays, strings, etc.
Use Case When the number of iterations is known When the number of iterations is unknown
Example:
js
// for loop
for (let i = 0; i < 3; i++) {
console.log(i); // 0, 1, 2
}
// while loop
let j = 0;
while (j < 3) {
console.log(j);
j++;
}
141/411
Q50. Difference between while and do...while loops?
Feature while Loop do...while Loop
Execution Condition First checks condition, then executes Executes at least once, then checks condition
Example:
js
Use Case Stops the loop completely Skips the current iteration, continues next
Example:
js
142/411
console.log(i); // 0, 1, 2, 4 (skips 3)
}
Use Works with index-based iteration (arrays, Iterates directly over values of iterables (arrays,
Case loops) strings)
Syntax for (let i = 0; i < arr.length; i++) for (let value of arr)
Example:
js
Use Iterates over values of an iterable (arrays, Iterates over keys (property names) of an
Case strings) object
Example:
js
143/411
let arr = ["Apple", "Banana", "Cherry"];
for (let fruit of arr) {
console.log(fruit); // "Apple", "Banana", "Cherry"
}
let obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
console.log(key, obj[key]); // "a 1", "b 2", "c 3"
}
Use Case Iterates over arrays Iterates over iterable values Iterates over object keys
Example:
js
// forEach()
arr.forEach(num => console.log(num * 2)); // 2, 4, 6
// for...of
for (let num of arr) {
console.log(num * 2); // 2, 4, 6
}
Best Use Case When needing break or continue When applying a function to each element
144/411
Use for...of when:
Conclusion
Use for loop for index-based iteration.
Use while loop when you don’t know how many times it should run.
🚀 Hope this clears your doubts on Loops in JavaScript! Let me know if you need more details. 😊
What are Functions in JS? What are the types of function?
01:26
Q57. Difference between named and anonymous functions?
01:48
Q58. What is function expression in JS?
01:11
Q59. What are Arrow Functions in JS? What is it use?
02:14
Q60. What are Callback Functions? What is it use?
02:26
Q61. What is Higher-order function In JS?
02:14
Q62. What is the difference between arguments and parameters?
00:44
Q63. In how many ways can you pass arguments to a function?
01:42
Q64. How do you use default parameters in a function?
00:56
Q65. What is the use of event handling in JS?
02:40
145/411
Q66. What are First-Class functions in JS?
01:25
Q67. What are Pure and Impure functions in JS?
02:57
Q68. What is Function Currying in JS?
02:34
Q69. What are call, apply and bind methods in JS?
9. Pure Functions – Functions that always return the same output for the same input.
Example:
js
// Named Function
function greet() {
return "Hello!";
146/411
}
js
Syntax:
js
✅ Shorter syntax
✅ Does not bind (useful in object methods and callbacks)
this
✅ Implicit return (if there’s only one statement)
🔹 Arrow function vs Regular function (difference in binding):
this
js
147/411
function traditional() {
console.log(this); // Refers to function caller
}
js
function sayBye() {
console.log("Goodbye!");
}
greet("Alice", sayBye);
// Output: Hello Alice
// Goodbye!
148/411
js
function multiplier(factor) {
return function(number) {
return number * factor;
};
}
Definition Actual values passed to a function Variables defined in the function declaration
js
js
149/411
function sum(...numbers) { // Rest Parameter
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
js
js
document.getElementById("btn").addEventListener("click", function() {
alert("Button clicked!");
});
150/411
const sayHello = () => "Hello!";
const greet = sayHello;
console.log(greet()); // "Hello!"
Definition Returns same output for same input May return different output for same input
Example:
js
// Pure Function
function add(a, b) {
return a + b;
}
js
function multiply(a) {
return function(b) {
return a * b;
};
}
const double = multiply(2);
console.log(double(5)); // 10
151/411
🔹 Use case: Creating reusable functions (e.g., setting tax rates, discounts).
call() fn.call(thisArg, arg1, arg2) Calls a function with a specified this value
apply() fn.apply(thisArg, [argsArray]) Similar to call() , but arguments are passed as an array
bind() fn.bind(thisArg, arg1, arg2) Returns a new function with this permanently set
Example:
js
function greet(city) {
console.log(this.name + " is from " + city);
}
Conclusion
Functions are the backbone of JavaScript programming. Understanding named vs anonymous
functions, arrow functions, callback functions, higher-order functions, and function methods ( call ,
apply , bind ) is key to mastering JS. 🚀
Let me know if you need further clarifications! 😊
What is a String?
00:19
Q71. What are template literals and string interpolation in strings?
01:31
Q72. Difference between single quotes (''), double quotes ("") &
152/411
backticks('') ?
00:37
Q73. What are some important string operations in JS?
02:10
Q74. What is string immutability?
01:34
Q75. In how many ways you can concatenate strings?
js
Strings in JavaScript are immutable, meaning their value cannot be changed after creation.
js
Multi-line Strings
js
153/411
Q72. Difference between Single Quotes ( ' ), Double Quotes ( " ), and
Backticks ( ` )?
Feature Single Quotes ( ' ) Double Quotes ( " ) Backticks ( ` )
Usage Common for strings Also common for strings Used for template literals
js
154/411
js
js
js
js
js
js
155/411
let words = ["Hello", "World"];
let sentence = words.join(" ");
console.log(sentence); // "Hello World"
Conclusion
Strings are immutable sequences of characters.
Various methods like slice() , replace() , and split() help in string manipulation.
156/411
Q86. What is the difference between createElement() and
createTextNode()?
What is DOM?
The Document Object Model (DOM) is a programming interface for web documents.
It represents the HTML structure as a tree-like hierarchy that can be accessed and manipulated
using JavaScript.
Q77. How do you Select, Modify, Create, and Remove DOM Elements?
1. Select Elements
js
2. Modify Elements
js
3. Create Elements
js
157/411
let newDiv = document.createElement("div");
newDiv.innerText = "New Element";
document.body.appendChild(newDiv);
4. Remove Elements
js
document.body.removeChild(newDiv);
158/411
Q80. What is the Difference Between querySelector() and
querySelectorAll() ?
js
2. Modify Attribute
js
document.getElementById("myInput").setAttribute("type", "password");
Q83. How to Add and Remove Properties of HTML Elements in the DOM Using
JS?
1. Add Property
js
159/411
document.getElementById("myDiv").customProperty = "Custom Value";
2. Remove Property
js
delete document.getElementById("myDiv").customProperty;
Q84. How to Add and Remove Styles from HTML Elements Using JS?
1. Add Style
js
document.getElementById("myDiv").style.color = "red";
2. Remove Style
js
document.getElementById("myDiv").style.removeProperty("color");
160/411
Conclusion
The DOM represents HTML elements as a tree structure that JS can manipulate.
js
try {
let result = 10 / 0; // No error, but may cause unexpected behavior
console.log(result);
161/411
Q88. What is the Role of the finally Block in JavaScript?
The finally block executes always, regardless of whether an error occurs or not.
js
try {
console.log("Trying...");
throw new Error("Something went wrong!");
} catch (error) {
console.error("Caught an error:", error.message);
} finally {
console.log("Finally block executed.");
}
Output:
vbnet
Trying...
Caught an error: Something went wrong!
Finally block executed.
js
function checkAge(age) {
if (age < 18) {
throw new Error("Age must be 18 or above!");
}
console.log("Access granted.");
}
162/411
try {
checkAge(16);
} catch (error) {
console.error(error.message);
}
Output:
nginx
js
function level1() {
level2(); // Calls another function
}
function level2() {
throw new Error("Error from level2"); // Error propagates
}
try {
level1();
} catch (error) {
console.error("Caught an error:", error.message);
}
Output:
vbnet
163/411
Q91. Best Practices for Error Handling in JavaScript
1. Use try...catch for expected errors
js
try {
let num = null;
console.log(num.length); // TypeError
} catch (error) {
if (error instanceof TypeError) {
console.error("Type Error:", error.message);
}
}
164/411
Summary
Error Handling is crucial for preventing program crashes.
165/411
An object in JavaScript is a collection of key-value pairs where keys are strings (or Symbols) and
values can be any data type.
Example of an Object
js
const person = {
name: "John",
age: 30,
isStudent: false,
greet: function () {
console.log("Hello, " + this.name);
},
};
console.log(person.name); // John
person.greet(); // Hello, John
js
166/411
user.name = "Alice";
js
Deleting a Property
js
delete user.age;
console.log(user); // { name: "Bob" }
167/411
Q97. Dot Notation vs. Bracket Notation
Feature Dot Notation Bracket Notation
When to Use When the key is a valid identifier When the key is dynamic or not a valid identifier
Example
js
js
js
js
168/411
Q99. How to Check if a Property Exists in an Object?
1️⃣ Using in Operator
js
js
console.log(user.hasOwnProperty("age")); // true
js
js
js
js
169/411
Type Shallow Copy Deep Copy
Example
js
let obj1 = { a: { b: 10 } };
let obj2 = { ...obj1 }; // Shallow copy
obj2.a.b = 20; // Changes obj1 too!
js
Example of Set
js
✅ Operations on Sets
js
170/411
Example of Map
js
✅ Operations on Maps
js
console.log(userMap.has("name")); // true
console.log(userMap.size); // 2
Performance Faster for frequent additions/removals Slower due to property access overhead
Summary
Objects store data in key-value pairs.
Shallow Copy vs. Deep Copy: Deep copy creates a full independent copy.
Set & Map: Set stores unique values, Map allows flexible key types.
171/411
What are Events? How are events triggered?
01:40
Q106. What are the types of events in JS?
01:05
Q107. What is Event Object in JS?
02:02
Q108. What is Event Delegation in JS?
02:01
Q109. What is Event Bubbling In JS?
01:40
Q110. How can you stop event propagation or event bubbling in
JS?
01:10
Q111. What is Event Capturing in JS?
01:42
Q112. What is the purpose of the event.preventDefault() method in
JS?
01:08
Q113. What is the use of "this" keyword in the context of event
handling in JS?
00:38
Q114. How to remove an event handler from an element in JS?
Events can be triggered by the user (e.g., clicking a button) or programmatically (e.g., using
dispatchEvent() ).
document.getElementById("btn").addEventListener("click", function() {
alert("Button Clicked!");
});
172/411
const event = new Event("click");
document.getElementById("btn").dispatchEvent(event);
173/411
document.getElementById("btn").addEventListener("click", function(event) {
console.log("Event Type:", event.type);
console.log("Clicked Element:", event.target);
});
document.getElementById("parent").addEventListener("click", function(event) {
if (event.target.classList.contains("child")) {
alert("Child element clicked!");
}
});
<div id="parent">
<button id="child">Click Me</button>
</div>
<script>
174/411
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent clicked!");
});
document.getElementById("child").addEventListener("click", () => {
console.log("Child clicked!");
});
</script>
Child clicked!
Parent clicked!
document.getElementById("child").addEventListener("click", function(event) {
event.stopPropagation();
console.log("Child clicked, but won't bubble up!");
});
Events travel from the root element down to the target element.
document.getElementById("parent").addEventListener("click", function() {
console.log("Parent clicked in capturing phase!");
}, true); // `true` enables capturing phase
175/411
✅ Output when clicking child button:
nginx
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
console.log("Form submission prevented!");
});
js
document.getElementById("btn").addEventListener("click", function() {
console.log(this.id); // Logs "btn"
});
176/411
js
function greet() {
alert("Hello!");
}
document.getElementById("btn").addEventListener("click", greet);
document.getElementById("btn").removeEventListener("click", greet);
Summary
Concept Explanation
177/411
Q121. What is the difference between a Regular Function and a
Closure?
Inner functions can access variables from their outer function but not vice versa.
function outer() {
let outerVar = "I am outer!";
function inner() {
console.log(outerVar); // ✅ Can access outerVar
}
inner();
}
outer();
📌 Key Takeaway:
The inner() function remembers the outerVar even though it is called inside outer() .
✅ Example: Closure
js
function outer() {
let count = 0; // Private variable
178/411
return function inner() {
count++; // Closure remembers `count`
console.log(count);
};
}
📌 Why?
The inner() function remembers count , even after outer() has finished execution.
function bankAccount(initialBalance) {
let balance = initialBalance;
return {
deposit(amount) {
balance += amount;
console.log(`Balance: ${balance}`);
},
withdraw(amount) {
if (amount <= balance) {
balance -= amount;
console.log(`Balance: ${balance}`);
} else {
console.log("Insufficient funds!");
}
}
};
}
179/411
const account = bankAccount(1000);
account.deposit(500); // Balance: 1500
account.withdraw(200); // Balance: 1300
console.log(account.balance); // ❌ Undefined (Encapsulated)
function counter() {
let count = 0; // Private variable
return {
increment() { count++; console.log(count); },
decrement() { count--; console.log(count); }
};
}
180/411
js
function createClosure() {
let largeArray = new Array(1000000).fill("data"); // Large memory usage
return function() {
console.log(largeArray.length);
};
}
Scope Access Can access only its own variables Can access outer function variables
Memory Usage Releases memory when function completes Holds variables in memory
Use Case Simple function calls Data privacy, event handlers, caching
// Regular Function
function regular() {
let count = 0;
count++;
console.log(count);
181/411
}
regular(); // Output: 1
regular(); // Output: 1 (doesn't remember previous count)
// Closure
function closure() {
let count = 0;
return function() {
count++;
console.log(count);
};
}
const counter = closure();
counter(); // Output: 1
counter(); // Output: 2 (remembers previous count)
📌 Key Difference:
A regular function forgets its variables after execution.
Closures Functions that keep access to outer function variables even after execution.
🚀 Closures are a powerful feature in JavaScript! Let me know if you need more examples.
What is asynchronous programming in JS? What is its use?
03:27
Q123. What is the difference between synchronous and
asynchronous programming?
01:39
Q124. What are the techniques for achieving asynchronous
operations in JS?
00:37
182/411
Q125. What is setTimeout()? How is it used to handle
asynchronous operations?
02:09
Q126. What is setInterval()? How is it used to handle asynchronous
operations?
01:33
Q127. What is the role of callbacks in fetching API data
asynchronously?
02:27
Q128. What is callback hell? How can it be avoided?
This is crucial for handling tasks like API calls, file operations, and timers without freezing the UI.
js
console.log("Start");
setTimeout(() => {
console.log("Asynchronous Task");
}, 2000);
console.log("End");
📌 Output:
pgsql
Start
End
Asynchronous Task (after 2 seconds)
👉 Use Cases of Asynchronous Programming: 1️⃣ Fetching API data (AJAX, Fetch API, Axios).
2️⃣ Handling user interactions without UI lag.
3️⃣ Running timers ( ,
setTimeout ).
setInterval
4️⃣ Working with files, databases, or external servers.
183/411
Q123. What is the Difference Between Synchronous and Asynchronous
Programming?
Feature Synchronous Asynchronous
Performance Slower, as it waits for each task to complete Faster, as multiple tasks run in parallel
Use Cases Simple calculations, loops API calls, file handling, animations
console.log("Task 1");
console.log("Task 2");
console.log("Task 3");
Output:
arduino
Task 1
Task 2
Task 3
console.log("Task 1");
setTimeout(() => {
console.log("Task 2 (Delayed)");
}, 2000);
console.log("Task 3");
Output:
arduino
184/411
Task 1
Task 3
Task 2 (Delayed)
📌 Key Difference:
Synchronous: Blocks execution until a task finishes.
Asynchronous: Moves to the next task immediately while waiting for previous ones.
Q124. What are the Techniques for Achieving Asynchronous Operations in JS?
1️⃣ Callbacks – Pass a function as an argument to be executed later.
2️⃣ Promises – Handle async operations with .then()and .
.catch()
3️⃣ Async/Await – A modern approach for writing cleaner async code.
4️⃣ Web APIs – setTimeout , ,
setInterval ,
fetch() .
XMLHttpRequest
js
console.log("Start");
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
console.log("End");
📌 Output:
pgsql
Start
End
Executed after 2 seconds
185/411
💡 Use Cases:
✔ Delaying API calls.
✔ Creating loading effects.
✔ Scheduling functions for later execution.
js
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Count: ${count}`);
if (count === 5) clearInterval(intervalId); // Stops after 5 times
}, 1000);
📌 Output:
makefile
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
💡 Use Cases:
✔ Updating UI dynamically.
✔ Creating countdown timers.
✔ Refreshing API data periodically.
186/411
✅ Example: Using a Callback in an API Request
js
function fetchData(callback) {
setTimeout(() => {
callback("Fetched Data");
}, 2000);
}
fetchData((data) => {
console.log(data); // Output: Fetched Data (after 2 sec)
});
setTimeout(() => {
console.log("Task 1");
setTimeout(() => {
console.log("Task 2");
setTimeout(() => {
console.log("Task 3");
}, 1000);
}, 1000);
}, 1000);
187/411
✅ How to Avoid Callback Hell? ✔ Use Promises – Replace nested callbacks with .then()
✔ Use Async/Await – Write clean and readable async code
executeTasks();
📌 Key Takeaways:
Callback Hell: Happens when multiple nested callbacks make code unreadable.
188/411
Concept Description
🚀 Next Steps: Learn Promises and Async/Await in-depth! Need more examples? Let me know!
Let's dive deeper into Promises and Async/Await in JavaScript! 🚀
🔹 Promises in JavaScript
What is a Promise?
A Promise is an object that represents the eventual completion or failure of an asynchronous
operation.
States of a Promise:
1️⃣ Pending – Initial state, operation not yet completed.
2️⃣ Fulfilled – Operation completed successfully.
3️⃣ Rejected – Operation failed.
✅ Creating a Promise
js
189/411
}
}, 2000);
});
javascript
Promise Resolved! ✅
Execution Completed! 🎉
📌 Output (if success is false ):
javascript
Promise Rejected! ❌
Execution Completed! 🎉
190/411
.then((msg) => console.log(msg))
.catch((err) => console.error(err)); // Handles any errors
📌 Output:
arduino
Task 1
Task 2
Task 3
🔹 Async/Await in JavaScript
What is Async/Await?
async and await are modern ways to handle asynchronous operations without using .then() .
fetchData();
📌 Output:
191/411
nginx
Fetching Data...
Processing Data...
Data Fetching Complete!
js
🔹 When to Use? ✔ When you need all tasks to complete before moving forward.
✅ Promise.race()
js
Task 3
🔹 When to Use? ✔ When you want the fastest response (e.g., loading indicator).
Execution Uses .then() for async handling Looks like synchronous code
Best For API calls, chaining async tasks Cleaner, maintainable async code
js
193/411
async function fetchUserData() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/users/1");
let user = await response.json();
console.log("User Data:", user);
} catch (error) {
console.error("Error fetching user data:", error);
}
}
fetchUserData();
📌 Output (Example):
json
User Data: {
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]"
}
194/411
console.error("Error fetching data:", error);
}
}
fetchUserAndPosts();
📌 Output (Example):
yaml
🔹 Why sequential?
✔ We need user ID before fetching user posts.
console.log("Users:", users);
console.log("Posts:", posts);
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchMultipleData();
📌 Why Promise.all() ?
✔ Fetches users and posts in parallel (faster performance).
✔ Saves time by not waiting for each request to complete before starting the next.
195/411
4️⃣ Handling Timeouts with setTimeout using Promises
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
fetchDataWithDelay();
📌 Output:
kotlin
Fetching data...
(Data appears after 3 seconds)
Data fetched! ✅
🔹 Why use Promises with setTimeout ?
✔ Allows async operations with controlled delays.
✅ Suppose an API call fails due to a network issue, and we want to retry it 3 times before giving up.
js
196/411
}
}
fetchWithRetry("https://jsonplaceholder.typicode.com/users/1")
.then(data => console.log("Fetched Data:", data))
.catch(error => console.error(error.message));
function getUser(callback) {
setTimeout(() => {
console.log("User fetched");
callback();
}, 1000);
}
function getPosts(callback) {
setTimeout(() => {
console.log("User's posts fetched");
callback();
}, 1000);
}
getUser(() => {
getPosts(() => {
console.log("All tasks completed!");
});
});
😵 Problem?
Hard to read & maintain due to nested callbacks.
197/411
js
fetchUserData();
198/411
🔹 Promises in JavaScript
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an
asynchronous operation and its resulting value.
Example of a Promise:
js
myPromise
.then(result => console.log(result))
.catch(error => console.error(error));
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
let success = true;
if (success) {
199/411
resolve("Data fetched successfully!");
} else {
reject("Failed to fetch data.");
}
}, 2000);
});
}
fetchData()
.then(data => console.log(data))
.catch(error => console.error(error));
🔹 Promise.all()
Promise.all() takes multiple promises and waits for all of them to resolve (or rejects if any one
fails).
Example:
js
const p1 = new Promise(resolve => setTimeout(() => resolve("🍕 Pizza Ready"), 2000));
const p2 = new Promise(resolve => setTimeout(() => resolve("🍔 Burger Ready"), 3000));
const p3 = new Promise(resolve => setTimeout(() => resolve("🍟 Fries Ready"), 1000));
200/411
Promise.all([p1, p2, p3])
.then(results => console.log("All food ready:", results))
.catch(error => console.error("Error:", error));
All food ready: [" 🍕 Pizza Ready", "🍔 Burger Ready", "🍟 Fries Ready"]
🔹 Key points: ✔ If all promises resolve → returns an array of results.
❌ If any one promise fails → entire Promise.all() fails.
🔹 Promise.race()
Promise.race() waits for the first Promise to resolve or reject.
Example:
js
const fast = new Promise(resolve => setTimeout(() => resolve("🚀 Fast Response"), 1000));
const slow = new Promise(resolve => setTimeout(() => resolve("🐢 Slow Response"), 3000));
Promise.race([fast, slow])
.then(result => console.log("First to resolve:", result))
.catch(error => console.error("Error:", error));
201/411
Feature Promise.all() Promise.race()
If one fails? Entire promise fails Still returns the first resolved/rejected promise
Use case When all results are needed When only the fastest result matters
The async/await syntax in JavaScript makes asynchronous code easier to read and write. It simplifies
working with Promises by allowing developers to write asynchronous code in a synchronous manner.
✅ Benefits of async/await :
✔ Improves code readability.
✔ Eliminates callback hell and .then() chains.
✔ Handles errors using try...catch (like synchronous code).
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => resolve(" ✅ Data fetched!"), 2000);
});
}
fetchData()
.then(result => console.log(result))
.catch(error => console.error(error));
202/411
✅ Data fetched!
Same Code Using async/await
js
fetchDataAsync();
Execution Flow Waits ( await ) before proceeding Uses .then() , doesn't pause execution
203/411
async function getData() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
}
getData();
📌 Output:
json
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
✔ You can declare an async function without await , but it behaves just like a regular function
returning a Promise.
js
204/411
2️⃣ Using await Without async
❌ Not possible!
✔ await can only be used inside an async function.
✔ Using it outside throws a SyntaxError.
js
fetchData();
📌 Output:
vbnet
205/411
return response.json();
}
fetchData()
.then(data => console.log(data))
.catch(error => console.error(" ❌ Error:", error.message));
✔ If an error occurs, it gets caught in .catch() .
🔹 Key Takeaways
✔ async makes a function return a Promise.
✔ await pauses execution until the Promise resolves.
✔ Easier to read compared to .then() chaining.
✔ Errors are handled using try...catch or .catch() .
206/411
🔹 Window Object in JavaScript
The window object is the global object in the browser that represents the browser window or tab.
✔ It provides methods and properties to interact with the browser.
207/411
fetch("https://jsonplaceholder.typicode.com/todos/1")
.then(response => response.json())
.then(data => console.log(data));
🔹 Local Storage
Stores data permanently (until deleted manually or by code).
js
// Store data
localStorage.setItem("username", "Merin");
// Retrieve data
console.log(localStorage.getItem("username")); // ✅ Output: "Merin"
// Remove data
localStorage.removeItem("username");
🔹 Session Storage
Stores data temporarily (clears when the tab is closed).
208/411
Example: Storing, Retrieving, and Removing Data
js
// Store data
sessionStorage.setItem("sessionKey", "SessionData");
// Retrieve data
console.log(sessionStorage.getItem("sessionKey")); // ✅ Output: "SessionData"
// Remove data
sessionStorage.removeItem("sessionKey");
Accessibility Accessible across all tabs/windows of the same origin Accessible only within the same tab
Use Case Storing user preferences, themes, tokens Temporary session data
209/411
Example: Creating and Reading Cookies
js
// Read cookies
console.log(document.cookie);
210/411
Q165. What are the best practices for improving performance in
JS?
let x = 10;
let y = 20;
console.log(eval("x + y")); // ✅ Output: 30
🚨 Why eval() is Dangerous? ✔ If user input is executed using eval() , it can lead to security
vulnerabilities like XSS attacks.
✔ Better Alternative: Use JSON.parse() or Function() instead of eval() .
js
js
document.getElementById("output").textContent = userInput;
211/411
🔹 What is SQL Injection Attack?
✔ SQL Injection is an attack where malicious SQL queries are injected into an application’s database
queries.
✔ If input is not sanitized, attackers can delete data, steal sensitive information, or modify the
database.
js
212/411
🔹 Best Practices for Improving Performance in JavaScript
⚡ 1. Use Efficient Loops: Avoid unnecessary iterations.
⚡ 2. Minimize DOM Manipulation: Batch updates instead of modifying elements frequently.
⚡ 3. Use & : Avoids unnecessary global scope usage.
let const
⚡ 4. Use async& for Asynchronous Code: Prevents blocking UI.
await
⚡ 5. Debounce & Throttle: Limits frequent function calls (e.g., for scroll events).
⚡ 6. Reduce Unused Variables & Functions: Avoids memory leaks.
⚡ 7. Optimize Images & Assets: Compress files for faster loading.
⚡ 8. Use Lazy Loading for Images & Data: Loads content only when needed.
⚡ 9. Use Caching (LocalStorage, IndexedDB, HTTP Caching): Reduces server load.
⚡ 10. Optimize JavaScript File Sizes: Minify & bundle JS files.
Example of Module:
js
// math.js (Module)
export function add(a, b) {
return a + b;
}
213/411
// main.js
import { add } from './math.js';
console.log(add(5, 3)); // Output: 8
✔ The export keyword is used to export functions, objects, or values from a module so that they can
be imported and used in other modules.
Example:
js
// Exporting a function
export function greet(name) {
return `Hello, ${name}!`;
}
// Exporting a constant
export const PI = 3.14159;
214/411
Named Exports
✔ You can export multiple variables or functions from a module with specific names.
✔ When importing, the exact name is required.
js
// Named Export
export const sum = (a, b) => a + b;
export function multiply(a, b) { return a * b; }
// Importing
import { sum, multiply } from './math.js';
Default Export
✔ You can export a single value as the default export.
✔ It can be imported with any name.
js
// Default Export
export default function subtract(a, b) { return a - b; }
// Importing
import sub from './math.js';
js
Dynamic Imports
✔ Dynamic imports allow you to import modules dynamically during runtime, often used for lazy
loading or code splitting.
215/411
✔ This returns a Promise.
js
Example:
bash
216/411
on a web page?
01:29
Q189. Feature that allows users to search for specific items in a
large dataset?
01:26
Q190. Feature that allows users to perform live search suggestions
as they type?
01:37
Q191. How to implement a real-time chat application using JS?
03:03
Q192. Create an infinite scrolling using JS when a user reaches the
webpage ?
01:25
Q193. Implement toggle switch to change the theme(light/dark
mode) of a website?
01:26
Q194. How to use JS to dynamically update date in real time on
webpage?
01:25
Q195. Prevent a form from being submitted without required
fields being filled?
Example:
html
<script>
const inputField = document.getElementById('username');
const errorMsg = document.getElementById('error-msg');
inputField.addEventListener('input', function() {
if (inputField.value.trim() === '') {
errorMsg.style.display = 'block';
} else {
217/411
errorMsg.style.display = 'none';
}
});
</script>
Example:
html
<div id="data"></div>
<button id="prev">Previous</button>
<button id="next">Next</button>
<script>
let currentPage = 1;
const itemsPerPage = 5;
const data = Array.from({ length: 50 }, (_, i) => `Item ${i + 1}`);
function renderPage() {
const startIndex = (currentPage - 1) * itemsPerPage;
const pageData = data.slice(startIndex, startIndex + itemsPerPage);
document.getElementById('data').innerHTML = pageData.join('<br>');
}
document.getElementById('next').addEventListener('click', () => {
if (currentPage * itemsPerPage < data.length) {
currentPage++;
renderPage();
}
});
document.getElementById('prev').addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
renderPage();
}
});
218/411
renderPage();
</script>
Example:
html
<script>
const dragElement = document.getElementById('drag');
const dropZone = document.getElementById('drop');
Q189. Feature that allows users to search for specific items in a large
dataset?
219/411
To implement a search feature, you can use an input field and filter the displayed data based on the
user's input.
Example:
html
<script>
document.getElementById('search').addEventListener('input', function() {
const searchQuery = this.value.toLowerCase();
const items = document.querySelectorAll('#list li');
items.forEach(item => {
if (item.textContent.toLowerCase().includes(searchQuery)) {
item.style.display = '';
} else {
item.style.display = 'none';
}
});
});
</script>
Q190. Feature that allows users to perform live search suggestions as they
type?
For live search suggestions, you can display suggestions dynamically based on the user's input.
Example:
html
<script>
const items = ['Apple', 'Banana', 'Cherry', 'Grape', 'Orange'];
220/411
document.getElementById('search').addEventListener('input', function() {
const query = this.value.toLowerCase();
const filteredItems = items.filter(item => item.toLowerCase().includes(query));
html
<script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
<script>
const socket = io('http://localhost:3000');
document.getElementById('send').addEventListener('click', () => {
const message = document.getElementById('message').value;
socket.emit('chatMessage', message);
});
Q192. Create an infinite scrolling using JS when a user reaches the webpage?
221/411
To implement infinite scrolling, you can use the scroll event and check if the user has scrolled to the
bottom of the page.
Example:
html
<div id="content"></div>
<script>
let page = 1;
function loadContent() {
for (let i = 1; i <= 10; i++) {
const item = document.createElement('div');
item.textContent = `Item ${((page - 1) * 10) + i}`;
document.getElementById('content').appendChild(item);
}
}
window.addEventListener('scroll', () => {
if (window.innerHeight + window.scrollY >= document.documentElement.scrollHeight) {
page++;
loadContent();
}
});
Example:
html
<script>
const themeToggle = document.getElementById('themeToggle');
222/411
themeToggle.addEventListener('click', () => {
document.body.classList.toggle('dark-theme');
});
</script>
<style>
body {
background-color: white;
color: black;
}
.dark-theme {
background-color: black;
color: white;
}
</style>
Example:
html
<div id="date-time"></div>
<script>
function updateDateTime() {
const date = new Date();
document.getElementById('date-time').textContent = date.toLocaleString();
}
setInterval(updateDateTime, 1000);
updateDateTime(); // Initial update
</script>
Q195. Prevent a form from being submitted without required fields being
filled?
You can use the required attribute on form fields or validate it using JavaScript before submission.
223/411
Example:
html
<form id="myForm">
<input type="text" id="username" required placeholder="Enter username">
<button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById('myForm');
form.addEventListener('submit', function(event) {
const username = document.getElementById('username');
if (!username.value.trim()) {
event.preventDefault();
alert('Username is required!');
}
});
</script>
224/411
02:21
Q204. Write a function to calculate the factorial of a number?
01:38
Q205. Write a program to remove all whitespace characters from a
string?
01:46
Q206. Write a function to find the sum of all elements in an array?
00:43
Q207. Write a function to find the average of an array of numbers?
00:33
Q208. Write a function to sort an array of numbers in ascending
order?
03:14
Q209. Write a function to check if an array is sorted in ascending
order or not?
01:41
Q210. Write a function to merge two arrays into a single sorted
array?
01:13
Q211. Write a function to remove a specific element from an array?
01:49
Q212. Write a function to find the second largest element in an
array?
01:19
Q213. Write a function to reverse the order of words in a given
sentence?
00:49
Q214. Function to find the longest common prefix among an array
of strings?
03:32
Q215. Write a function to find the intersection of two arrays?
01:32
Q216. Write a function to calculate the Fibonacci sequence up to a
given number?
function reverseString(str) {
return str.split('').reverse().join('');
}
225/411
console.log(reverseString("hello")); // Output: "olleh"
Q197. Write a function that returns the longest word in the sentence?
javascript
function longestWord(sentence) {
const words = sentence.split(' ');
let longest = '';
for (let word of words) {
if (word.length > longest.length) {
longest = word;
}
}
return longest;
}
function isPalindrome(str) {
const cleanedStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
return cleanedStr === cleanedStr.split('').reverse().join('');
}
226/411
function removeDuplicates(arr) {
return [...new Set(arr)];
}
Q200. Write a function that checks whether two strings are anagrams or not?
javascript
function countVowels(str) {
const vowels = 'aeiouAEIOU';
return str.split('').filter(char => vowels.includes(char)).length;
}
function largestNumber(arr) {
return Math.max(...arr);
}
227/411
console.log(largestNumber([3, 5, 7, 2, 8])); // Output: 8
function isPrime(num) {
if (num < 2) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
javascript
function factorial(n) {
if (n === 0 || n === 1) return 1;
return n * factorial(n - 1);
}
function removeWhitespace(str) {
return str.replace(/\s+/g, '');
}
228/411
console.log(removeWhitespace("Hello World ")); // Output: "HelloWorld"
function sumArray(arr) {
return arr.reduce((sum, num) => sum + num, 0);
}
function averageArray(arr) {
return arr.reduce((sum, num) => sum + num, 0) / arr.length;
}
function sortArray(arr) {
return arr.sort((a, b) => a - b);
}
229/411
Q209. Write a function to check if an array is sorted in ascending order or
not?
javascript
function isSorted(arr) {
return arr.every((val, i) => i === 0 || val >= arr[i - 1]);
}
Q210. Write a function to merge two arrays into a single sorted array?
javascript
230/411
function secondLargest(arr) {
let uniqueArr = [...new Set(arr)].sort((a, b) => b - a);
return uniqueArr[1];
}
function reverseWords(sentence) {
return sentence.split(' ').reverse().join(' ');
}
Q214. Function to find the longest common prefix among an array of strings?
javascript
function longestCommonPrefix(arr) {
if (arr.length === 0) return "";
let prefix = arr[0];
for (let i = 1; i < arr.length; i++) {
while (arr[i].indexOf(prefix) !== 0) {
prefix = prefix.slice(0, -1);
}
}
return prefix;
}
231/411
Q215. Write a function to find the intersection of two arrays?
javascript
function fibonacci(n) {
let fib = [0, 1];
for (let i = 2; i < n; i++) {
fib.push(fib[i - 1] + fib[i - 2]);
}
return fib;
}
Let me know if you need further assistance with any of the above functions! 😊
Q. What is HTML? Differences between HTML & HTML5?
Advantages of HTML5?
04:47
Q. What is the difference between HTML and XHTML?
02:33
Q. What is the role of DOCTYPE in HTML?
01:25
Q. What if you remove <!DOCTYPE html> from your HTML?
00:33
Q. Difference between Head & Body in HTML? Where to place JS
link reference?
02:15
232/411
Q. What is Title Tag in HTML? What are the 4 advantages of Title
tag?
01:55
Q. What are Meta Tags? What are the 5 types of meta tags?
1. Doctype Declaration: HTML5 uses <!DOCTYPE html> , while older versions like HTML4 use
<!DOCTYPE HTML PUBLIC...> .
2. New Elements: HTML5 introduces new semantic elements like <header> , <footer> ,
<section> , <article> , and <nav> , which help structure the content better.
3. Multimedia Support: HTML5 supports native video and audio elements ( <video> and
<audio> ) without needing plugins.
4. Forms: HTML5 provides new input types such as email , date , range , and more.
5. APIs: HTML5 comes with integrated APIs like Geolocation, Web Storage, and WebSockets.
Advantages of HTML5:
XHTML (Extensible HTML) is a stricter version of HTML based on XML. Some key differences:
233/411
1. XHTML requires all tags to be properly closed (e.g., <img src="image.jpg" /> ), while HTML
allows self-closing tags to be optional.
2. XHTML elements must be written in lowercase (e.g., <body> ), while HTML is case-insensitive.
Difference between Head & Body in HTML? Where to place JS link reference?
Head ( <head> ):
Contains metadata about the document, like title, meta tags, link to stylesheets, and other
resources.
Body ( <body> ):
Contains the actual content that appears on the page, such as text, images, and other
elements.
Ideally, JavaScript should be placed at the end of the <body> tag or inside the <head> tag
with the async or defer attribute.
Placing JavaScript at the end of the body helps avoid blocking the rendering of the page
content.
234/411
What is Title Tag in HTML? What are the 4 advantages of Title tag?
The <title> tag defines the title of the webpage, which appears on the browser's title bar or tab.
1. Improves SEO (Search Engine Optimization) by providing a clear description of the page.
2. Helps users quickly identify the page in browser tabs or search results.
What are Meta Tags? What are the 5 types of meta tags?
Meta tags provide metadata about the HTML document, like description, keywords, and author,
which is used by search engines and browsers.
1. Meta Description: Provides a brief summary of the page content for search engines.
html
2. Meta Keywords: Contains keywords related to the page for SEO purposes.
html
html
4. Meta Charset: Defines the character encoding for the page (e.g., UTF-8).
html
<meta charset="UTF-8">
5. Meta Robots: Directs search engine crawlers on how to index or follow links on the page.
235/411
html
What are HTML elements? What is the difference between Element & Tag?
HTML Elements: An HTML element is a combination of an opening tag, content, and a closing tag.
For example:
html
<p>This is a paragraph.</p>
Here, <p> is the opening tag, This is a paragraph. is the content, and </p> is the closing tag.
The entire structure is considered an HTML element.
236/411
A Tag is the markup that denotes the beginning or end of an HTML element (e.g., <p> is an
opening tag, </p> is a closing tag).
An Element refers to the complete combination of the opening tag, content, and closing tag
(e.g., <p>This is a paragraph.</p> is a paragraph element).
What are the roles and uses of the <div> element in HTML?
The <div> element is a block-level container used to group together other HTML elements. It is
commonly used for layout purposes, as it allows you to structure content into sections without
adding any semantic meaning to it.
Uses of <div> :
html
<div class="container">
<p>Content goes here.</p>
</div>
<span> is an inline element, which means it only takes up as much width as its content and does
not start on a new line. It is used for styling smaller sections of text or inline content.
Example:
html
<div>Block-level content</div>
<span>Inline content</span>
237/411
What is the role of <p> , <a> , <br> , <hr> , <em> , <img> , <input> , & <button>
elements in HTML?
<p> : Defines a paragraph. Used to structure text into separate blocks.
html
<p>This is a paragraph.</p>
html
<br> : Defines a line break. Used to insert a single line break in text.
html
Hello<br>World!
<hr> : Defines a horizontal rule. Used to create a thematic break in a page (usually displayed as a
line).
html
<hr>
<em> : Defines emphasized text. It is typically displayed in italics and used for stressing words.
html
<em>Important</em> text.
html
<input> : Defines an input field in forms, where the user can enter data.
html
<button> : Defines a clickable button. Typically used to trigger actions when clicked.
238/411
html
<button>Click Me</button>
html
<header>
<h1>Website Title</h1>
</header>
<main> : Represents the main content of the document. It is used to highlight the primary content
of the page.
html
<main>
<p>Main content goes here.</p>
</main>
<section> : Represents a section of content, often with a specific theme or purpose, like a chapter
or a group of related content.
html
<section>
<h2>About Us</h2>
<p>Content here...</p>
</section>
<footer> : Represents the footer section of a document or a section, typically containing metadata
or copyright information.
html
<footer>
<p>© 2025 Your Company</p>
</footer>
239/411
<address> : Represents contact information for the author or owner of a document or section.
html
<address>
<p>Contact us at: [email protected]</p>
</address>
What is the role of Heading tags in HTML? How does it impact SEO?
Heading tags ( <h1> , <h2> , <h3> , etc.) define headings and subheadings in a webpage, used to
organize content hierarchically.
Impact on SEO:
1. Organizes Content: Helps search engines understand the structure and context of the
content.
2. Improves Accessibility: Allows screen readers and assistive technologies to identify and
navigate the content more easily.
3. Boosts Keyword Relevance: Headings (especially <h1> ) often include important keywords
that impact ranking on search engines.
It is recommended to use headings in a logical hierarchy (e.g., <h1> for the main title, <h2> for
subheadings).
html
<section>
<h2>Introduction</h2>
<p>Content about the introduction.</p>
</section>
<article> : Represents a self-contained piece of content, such as a blog post, news story, or user
comment, that can be distributed or reused independently.
240/411
html
<article>
<h2>Blog Post Title</h2>
<p>Content of the blog post...</p>
</article>
These explanations should clarify the different roles and uses of HTML elements. Let me know if you'd
like further details!
html
<html>
<head></head>
<body></body>
</html>
Parent Element: An element that contains one or more other elements. For example, in this
snippet, <div> is the parent of <p> :
241/411
html
<div>
<p>This is a paragraph.</p>
</div>
Child Element: An element that is inside another element. In the example above, <p> is the child
of <div> .
Nested Elements: Elements that are placed inside other elements. Nested elements can be
parents or children depending on their position in the structure.
html
<div>
<section>
<p>Nested content.</p>
</section>
</div>
Examples:
html
242/411
Semantic Elements: These elements clearly describe their meaning in both the browser and
developer's context. They improve accessibility, SEO, and code readability.
These elements provide meaning about the structure of the content. For example, <article> is
for a self-contained piece of content like a blog post, and <header> defines the header section.
No, the <div> element is not a semantic element. It is a non-semantic container that has no
meaning on its own but is used for grouping content for styling or scripting purposes.
html
<div class="container">
<p>This is a paragraph inside a div.</p>
</div>
Example:
html
<DIV>
<P>Hello, World!</P>
</DIV>
However, it is recommended to use lowercase for tags for consistency and readability, as per
modern HTML standards.
Block-Level Elements: Occupy the full width of their parent container and start on a new line
(e.g., <div> , <p> ).
243/411
Inline Elements: Only take up as much width as necessary and do not start on a new line (e.g.,
<span> , <a> ).
Inline Elements: Do not accept width and height properties (they are determined by their
content).
3. Structure:
<div>
<p>
<section>
<article>
<header>
<footer>
<nav>
<aside>
<form>
<blockquote>
<pre>
<hr>
Inline Elements:
<span>
<a>
244/411
<strong>
<em>
<img>
<b> , <i>
<u>
<abbr>
<code>
<sub> , <sup>
<q>
<br> (although technically a self-closing tag, it behaves as inline in the document flow)
These are the explanations for the HTML-related concepts you're asking about! Let me know if you'd
like any more details.
What are HTML Attributes? What are the Types of HTML attributes?
01:49
Q. What are the Id, Style & Class attributes of an element? When to
use what?
02:36
Q. What will happen if two elements have same ids?
01:21
Q. Multiple Classes for single element? Style precedence?
01:16
Q. What are Data Attributes in HTML?
What are HTML Attributes? What are the Types of HTML attributes?
HTML Attributes: Attributes in HTML provide additional information about an element, such as its
behavior, style, or properties. They are written inside the opening tag of an element and are made
up of a name and a value pair.
Example:
html
245/411
<a href="https://example.com" target="_blank">Visit Example</a>
1. Global Attributes: These can be used with any HTML element (e.g., id , class , style ,
title ).
2. Event Attributes: These are used to handle events (e.g., onclick , onload , onmouseover ).
3. Form-related Attributes: These are used in form elements (e.g., action , method , name ,
value ).
4. Image-related Attributes: These are used with <img> elements (e.g., src , alt , width ,
height ).
5. Link-related Attributes: These are used with links (e.g., href , rel , type ).
What are the Id, Style & Class attributes of an element? When to use what?
id Attribute:
Purpose: Assigns a unique identifier to an element. Each id should be unique within the
document.
When to use: Use it when you need to target an element uniquely with JavaScript or CSS.
Example:
html
style Attribute:
When to use: Use it when you want to apply styles to an element temporarily, but it’s better to
use an external CSS file for maintainability.
Example:
html
class Attribute:
246/411
Purpose: Used to define one or more classes that an element belongs to. Classes can be
shared across multiple elements.
When to use: Use it when you want to group elements and apply the same style or behavior
across multiple elements.
Example:
html
html
In this case, both <div> elements have the same id of "header," which is not recommended. Use
classes for multiple elements instead of id .
Example:
html
247/411
Style Precedence: When multiple CSS rules apply to the same element, the specificity of the
selector determines which style takes precedence:
2. IDs.
If two classes apply conflicting styles, the last defined class in the list will take precedence.
Example:
html
<style>
.red { color: red; }
.blue { color: blue; }
</style>
<div class="red blue">This will be blue</div>
Example:
html
In JavaScript, you can access these data attributes via the dataset property:
javascript
Use: Data attributes are commonly used for storing additional information that you need to access
via JavaScript without affecting the presentation of the element.
248/411
Let me know if you'd like further clarification on any of these topics!
Example:
html
2. External Links: These links point to a different website or domain. They use full URLs (absolute
URLs).
Example:
html
3. Anchor Links (Fragment Links): These are used to navigate to a specific section within the same
page. It uses the id attribute to target a specific element.
249/411
Example:
html
4. Mailto Links: These are used to create links that open the user's email client and automatically
populate the "To" field with a specified email address.
Example:
html
5. Telephone Links: These links allow users to dial a phone number directly from the web page
(mostly used on mobile devices).
Example:
html
Example:
html
<a href="https://www.example.com/contact.html">Contact</a>
Relative URL: A relative URL provides the path to a resource relative to the current page's location.
It does not include the domain name or protocol, making it shorter and more flexible for internal
navigation within the same website.
Example:
html
<a href="about.html">About</a>
250/411
What is the purpose of the <nav> element in HTML?
The <nav> element is used to define a navigation section in an HTML document. It typically
contains a list of links used for navigation within the website or application. It helps search engines
and screen readers understand that the enclosed links are for navigation purposes.
Example:
html
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
Example:
html
Here, #section1 is the fragment identifier that points to the element with the id="section1" .
251/411
Example:
html
<head>
<base href="https://www.example.com/">
</head>
<body>
<a href="about.html">About Us</a> <!-- This will point to
https://www.example.com/about.html -->
</body>
Example:
html
<head>
<link rel="stylesheet" href="styles.css">
</head>
This will link the styles.css file to the HTML document, applying the styles defined in it.
Example:
html
252/411
How do you create an Email Link?
To create an email link, you use the mailto: protocol in the href attribute. When clicked, this link
will open the default email client with a new email draft.
Example:
html
html
1. Ordered List ( <ol> ): A list where the items are numbered or ordered. Each item in the list is
wrapped in an <li> tag.
253/411
Example:
html
<ol>
<li>First Item</li>
<li>Second Item</li>
<li>Third Item</li>
</ol>
2. Unordered List ( <ul> ): A list where the items are not numbered, and typically represented with
bullets. Each item in the list is wrapped in an <li> tag.
Example:
html
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
3. Definition List ( <dl> ): A list of terms and their definitions. Each term is wrapped in a <dt>
(definition term) tag, and each definition is wrapped in a <dd> (definition description) tag.
Example:
html
<dl>
<dt>HTML</dt>
<dd>A markup language for creating web pages.</dd>
<dt>CSS</dt>
<dd>A style sheet language for styling HTML elements.</dd>
</dl>
Example:
html
254/411
<ul>
<li>Item 1</li>
<li>Item 2
<ul>
<li>Sub-item 2.1</li>
<li>Sub-item 2.2</li>
</ul>
</li>
<li>Item 3</li>
</ul>
What are table, tr, th, td elements? What are the advantages & disadvantages
of tables?
1. <table> : Defines the table itself.
Example:
html
<table>
<!-- Table content here -->
</table>
Example:
html
<tr>
<!-- Table row content -->
</tr>
3. <th> : Defines a header cell in a table, typically bold and centered. It is used within a <tr> to
specify column headings.
Example:
html
<th>Header 1</th>
255/411
4. <td> : Defines a data cell in a table. It is used to define regular table content within a row.
Example:
html
<td>Data 1</td>
Structured Data Representation: Tables are great for displaying structured data, such as rows and
columns, and are commonly used in financial, statistical, or tabular data.
Easy to Use: HTML tables provide an easy way to display data in a grid-like structure.
Accessibility Issues: Tables can be challenging for screen readers and assistive technologies,
especially if they are not marked up with proper <th> and <caption> elements.
Not Responsive by Default: Tables can be challenging to make responsive without additional CSS
or JavaScript, especially when the content is too wide for mobile devices.
Example:
html
<table>
<tr>
<th colspan="2">Header spanning two columns</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
256/411
What is the best way to add a border to a table, column, and cell?
The best way to add borders to tables, columns, and cells is by using CSS. You can specify borders
using the border property.
html
html
While you can't directly add borders to columns in HTML, you can style all cells within a specific column
using CSS selectors like nth-child .
Example:
html
<style>
td:nth-child(1), th:nth-child(1) {
border-left: 2px solid black;
}
td:nth-child(2), th:nth-child(2) {
border-right: 2px solid black;
}
</style>
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Data 1</td>
<td>Data 2</td>
</tr>
</table>
257/411
This method can be used to style borders for specific columns.
Example:
html
alt (Alternative text): Provides a text alternative for the image if it can't be displayed. It is crucial
for accessibility because screen readers use the alt text to describe images to visually impaired
users. It also improves SEO and helps when the image is missing or not loaded.
258/411
2. SEO: Search engines use the alt text to understand the content of the image and index it
properly.
3. Fallback: If the image fails to load, the alt text will be displayed instead.
What are the differences between JPEG and PNG image formats?
JPEG (Joint Photographic Experts Group):
Quality: Lower image quality with higher compression, leading to some loss of detail and
sharpness.
Best for: Images with transparency or images requiring sharpness, such as logos, icons, and
images with text.
Example:
html
<video controls>
<source src="video.mp4" type="video/mp4">
<source src="video.ogv" type="video/ogg">
259/411
<source src="video.webm" type="video/webm">
Your browser does not support the video tag.
</video>
Why multiple <source> elements?: Different browsers support different video formats. For
instance, some browsers may support MP4, while others support Ogg or WebM. By providing
multiple sources, you ensure that the video will play in most browsers.
Example:
html
<audio controls>
<source src="audio.mp3" type="audio/mp3">
<source src="audio.ogg" type="audio/ogg">
Your browser does not support the audio element.
</audio>
controls : Adds play, pause, and volume controls to the audio player.
The autoplay attribute automatically starts playing the media (video or audio) as soon as it is
ready, without user interaction.
Example:
html
<audio autoplay>
<source src="audio.mp3" type="audio/mp3">
</audio>
260/411
Note: Autoplay may be restricted in certain browsers, particularly for videos with sound, due
to user experience considerations.
2. Loop:
The loop attribute causes the media to restart automatically after it ends, creating a
continuous playback loop.
Example:
html
<video loop>
<source src="video.mp4" type="video/mp4">
</video>
261/411
Advantages:
1. User Interaction: Forms provide a way for users to input data and interact with websites.
2. Data Submission: They are used to submit data to a server for processing, like registration, login,
or feedback.
3. Customization: Forms can include different types of fields (text, radio buttons, checkboxes, etc.),
making them highly customizable.
4. Validation: HTML forms allow for both client-side and server-side validation of user input.
1. <input>:
Used for various input types like text, password, checkbox, etc.
2. <textarea>:
3. <button>:
4. <select>:
5. <label>:
Attributes: for
262/411
How to Validate for empty input field in form?
To validate an empty input field in an HTML form, you can use the required attribute in the <input>
element. This will prevent form submission if the field is left empty.
Example:
html
<form>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>
In this case, if the user tries to submit the form without entering a name, the browser will display a
message and prevent submission.
Attributes:
Example:
html
263/411
1. text: Single-line text input.
Example:
html
1. Radio buttons allow the user to select only one option from a group of options.
Example:
html
Grouping: Use the same name attribute for all radio buttons in the same group, as shown in
the example above. This ensures that only one radio button can be selected at a time.
264/411
Example:
html
Grouping: Checkboxes are grouped by using the same name attribute, but unlike radio
buttons, they can be selected independently.
Example:
html
Attributes: name is used to associate the element with a name, which is sent with the form data.
You can also use multiple if you want users to select multiple options.
265/411
What are Top 10 Best Practices for Writing HTML Code?
1. Use Semantic HTML Tags:
Use semantic elements like <header> , <footer> , <main> , <section> , etc., to improve
accessibility and SEO.
Indent your HTML code consistently to improve readability. Use 2 or 4 spaces for indentation,
depending on your project style guide.
Use meaningful and descriptive names for IDs and classes to make your code more readable
and maintainable.
Use external CSS files to style your pages, rather than using inline styles, which makes the
code harder to maintain.
Always include an alt attribute for images to improve accessibility and provide context for
search engines.
Add proper ARIA attributes and labels to improve accessibility for screen readers.
Use tools like the W3C Markup Validation Service to validate your HTML to ensure that your
code is free from errors and conforms to standards.
Instead of embedding large chunks of CSS and JavaScript in the HTML file, link to external files
to keep your HTML clean and minimize page load time.
Use more meaningful HTML5 semantic elements instead of relying on <div> and <span>
which are non-semantic.
Ensure that every document has the correct structure: <!DOCTYPE html> , <html> , <head> , and
<body> tags.
266/411
What is HTML5 Boilerplate Code?
HTML5 Boilerplate is a set of standard templates, configurations, and tools for building fast, robust,
and adaptable web apps or websites. It includes basic structure for HTML, CSS resets, and essential
JavaScript to ensure your website works well across different devices and browsers. The HTML5
Boilerplate also improves website performance and ensures best practices for web development.
Minification removes unnecessary spaces, comments, and characters to reduce file size and
improve page loading speed.
Load JavaScript asynchronously using the async or defer attribute to avoid blocking HTML
rendering.
Use proper HTTP headers to instruct browsers to cache static assets like images, stylesheets,
and scripts for future visits.
4. Optimize Images:
Compress and use appropriate image formats (e.g., WebP) to reduce the file size and loading
time.
Minimize the number of requests made to the server by combining CSS and JavaScript files,
and reducing the number of images used.
Load images and other content only when they are needed (e.g., when they are in the
viewport).
Host static files (like images, CSS, and JavaScript) on CDNs to serve them from locations closer
to the user, improving loading times.
267/411
8. Enable GZIP Compression:
Use GZIP compression to reduce the size of your HTML, CSS, and JavaScript files before
sending them to the browser.
Ensure each page has a unique and descriptive <title> tag to summarize the page content.
Use relevant <meta> tags like description and keywords to provide additional information
about the page.
Proper use of semantic tags (e.g., <article> , <header> , <footer> ) improves content clarity
and accessibility, which boosts SEO.
Use responsive web design techniques (like the viewport meta tag) to ensure your site works
well on all screen sizes, which is important for SEO.
Provide descriptive alt text for images to help search engines understand the content of the
images and improve image search results.
Ensure all your HTML, CSS, JavaScript, and image files are ready and properly organized for
deployment.
2. Test Locally:
Test your website locally to ensure it works properly across different browsers and devices.
268/411
3. Choose a Web Hosting Provider:
Select a web hosting provider that suits your needs (e.g., shared hosting, VPS, or cloud
hosting).
Upload your website files to the hosting server using FTP/SFTP or a web hosting control panel
(e.g., cPanel).
Set up your domain name and point it to your hosting provider by updating the DNS settings
to ensure your website is accessible.
What are the Top 3 Things Required to Make a Website Responsive in HTML?
269/411
1. Viewport Meta Tag:
Use percentage-based widths instead of fixed pixel widths for the layout. This allows elements
to scale proportionally according to the screen size.
3. Media Queries:
Use CSS media queries to apply different styles based on the screen size, orientation, and
resolution. This allows for changing layout, font sizes, or other styles based on the device’s
characteristics.
What are Some Responsive Design Frameworks for HTML & CSS?
1. Bootstrap:
A widely used framework that provides a grid system, pre-built responsive design
components, and CSS utilities for mobile-first design.
2. Foundation:
A responsive front-end framework that offers a flexible grid system and mobile-first
components, which can be customized according to your needs.
3. Tailwind CSS:
A utility-first CSS framework that allows developers to build custom responsive designs with
minimal effort by using pre-defined utility classes.
What are HTML Entities? How do you Display Special Characters in HTML?
HTML Entities are special codes that represent characters that may have special meanings in HTML
(like < , > , or & ), or characters that are not easily typed on a keyboard, such as accented letters or
mathematical symbols. They are written as &entity; , such as < for < , > for > , and &
for & .
You can display special characters by using their corresponding HTML entity codes in your HTML
markup. For example:
270/411
< represents <
© represents ©
HTML5 continues to evolve, offering new semantic elements like <article> , <section> ,
<nav> , and <footer> , which improve SEO, accessibility, and content structure.
2. Web Components:
Web Components allow developers to create reusable custom elements with encapsulated
styles and functionality, promoting modular design and reusability.
PWAs provide a native app-like experience using HTML, CSS, and JavaScript, allowing websites
to work offline, load quickly, and be installed on mobile devices.
4. Improved Accessibility:
Increased focus on creating accessible websites with better use of ARIA (Accessible Rich
Internet Applications) roles, labels, and attributes, ensuring that websites are usable by people
with disabilities.
5. Responsive Images:
The use of the <picture> element and srcset attribute allows developers to deliver different
image sizes based on the screen resolution or device, improving loading times and
performance.
271/411
01:36
Q. What are the 5 advantages of external stylesheet?
01:41
Q. How do you Include CSS in a webpage or HTML?
00:41
Q. How to implement CSS using @import rule?
02:01
Q. What is CSS Preprocessors? What is SCSS?
03:11
Q. What are the 3 Types of CSS Preprocessors?
1. Inline CSS: Directly within the HTML element using the style attribute.
2. Internal CSS: Defined within the <style> tag in the <head> section of the HTML document.
3. External CSS: Linked to an HTML document through an external CSS file using the <link> tag.
4. CSS @import Rule: Imports external CSS files into a CSS file.
5. CSS in JavaScript (CSS-in-JS): Defining CSS directly inside JavaScript files, commonly used with
modern frameworks like React.
html
When to Use:
272/411
Inline styles are rarely used for large applications but can be useful for quick, specific styling on a
single element.
It is best used for dynamically generated content (e.g., in JavaScript) or if styles need to be applied
conditionally on a single element.
When to Use:
When you want to apply CSS to a single page only, without affecting other pages in the website.
It is useful for small websites or prototypes where external CSS might not be necessary.
html
<head>
<style>
p {
color: blue;
}
</style>
</head>
When to Use:
Ideal for large websites where you need to apply the same styles across multiple pages.
html
<head>
<link rel="stylesheet" href="styles.css">
273/411
</head>
2. Reusability: The same stylesheet can be applied to multiple web pages, reducing redundancy.
3. Improved Load Time: External CSS files can be cached by browsers, reducing page load times for
subsequent visits.
4. Easier Maintenance: Changes in the stylesheet are automatically reflected across all linked HTML
pages, making updates easier.
5. Cleaner Code: HTML files remain cleaner and more readable, without inline or internal CSS clutter.
2. Internal CSS: Using a <style> tag in the <head> section of the HTML document.
3. External CSS: Linking to an external CSS file using the <link> tag.
css
@import url("styles.css");
Note: @import can also be used in the <style> section, but using it in external files might cause
slower page load times compared to using <link> .
274/411
What is CSS Preprocessors? What is SCSS?
CSS Preprocessors are scripting languages that extend CSS with features like variables, nesting,
mixins, and functions, making CSS easier to write and maintain. The most popular CSS preprocessors
are Sass, LESS, and Stylus.
SCSS (Sassy CSS) is a syntax of Sass (Syntactically Awesome Stylesheets). It provides the same features
as Sass but with a syntax more similar to regular CSS, allowing you to write CSS inside .scss files.
2. LESS: A preprocessor that extends CSS with variables, mixins, and functions, offering easier and
more maintainable code.
3. Stylus: A CSS preprocessor similar to Sass and LESS, but with a more flexible syntax that allows for
optional semicolons, braces, and parentheses.
275/411
What are Selectors in CSS? How Many Types of Selectors Are There?
Selectors in CSS are used to select HTML elements on which styles will be applied. They target specific
elements based on various criteria like their type, class, id, attributes, or relationship to other
elements.
2. Type Selector (Element Selector): Selects all elements of a specific type (e.g., p , h1 , div ).
Difference Between ID, Element & Class Selector? When to Use Which
Selector?
ID Selector ( #idname ):
Use it when you want to apply styles to all instances of that element type.
Targets elements with a specific class attribute, allowing you to apply styles to multiple
elements.
276/411
Use it when you want to apply the same style to several elements.
Example:
css
* {
margin: 0;
padding: 0;
}
This rule removes margins and padding from every element on the page.
Example:
css
div p {
color: red;
}
This targets all <p> elements inside any <div> element, regardless of how deeply nested they are
within <div> .
277/411
The five types of attribute selectors are:
1. [attr] : Selects elements that have the specified attribute. Example: [type] (selects all elements
with a type attribute).
3. [attr~="value"] : Selects elements whose attribute value contains a specified word (separated by
spaces). Example: [class~="btn"] (selects elements with a class that contains the word "btn" ).
4. [attr|="value"] : Selects elements with an attribute value that starts with the specified value or is
an exact match with the specified value, followed by a hyphen. Example: [lang|="en"] (selects
elements with a lang attribute value of "en" or "en-US" ).
5. [attr^="value"] : Selects elements whose attribute value starts with the specified value. Example:
[href^="https"] (selects links starting with https ).
6. [attr$="value"] : Selects elements whose attribute value ends with the specified value. Example:
[src$=".jpg"] (selects images ending with .jpg ).
Example:
css
div > p {
color: green;
}
This will only select <p> elements that are direct children of a <div> , not deeper nested <p>
elements.
Descendant Selector (space): Selects all descendants (children, grandchildren, etc.) of a parent
element, regardless of depth.
278/411
Example:
css
/* Child Selector */
div > p {
color: blue;
}
/* Descendant Selector */
div p {
color: red;
}
The child selector only targets <p> elements directly inside a <div> , while the descendant selector
targets all <p> elements inside a <div> , including nested ones.
Example:
css
a:hover {
color: red;
}
Pseudo-element Selector ( :: ): Targets specific parts of an element, such as the first letter or line
of a text, or content before or after an element.
Example:
279/411
css
p::first-letter {
font-size: 2em;
}
Here are the explanations for the concepts related to the Box Model and CSS positioning:
2. Padding: The space between the content and the border. It is used to create space around the
content inside the element.
3. Border: The boundary surrounding the padding (and content). It can have various styles, widths,
and colors.
4. Margin: The outermost space around the border. It separates the element from other surrounding
elements.
280/411
Here’s a visual representation:
lua
+----------------------------+
| Margin |
| +------------------------+ |
| | Border | |
| | +------------------+ | |
| | | Padding | | |
| | | +------------+ | | |
| | | | Content | | | |
| | | +------------+ | | |
| | +------------------+ | |
| +------------------------+ |
+----------------------------+
sql
Total width = content width + left padding + right padding + left border + right border +
left margin + right margin
Margin is the space outside the element, between the border and the surrounding elements. It
creates space between the element and other elements.
Key Differences:
1. Padding affects the size of the element (content area), but Margin does not.
2. Padding is part of the element's box and can be styled, whereas Margin separates elements from
each other.
281/411
The element is displayed inline with other content, meaning it doesn't start on a new line.
Cannot have width, height, or vertical margin/padding applied (though it can have horizontal
padding/margin).
display: block :
The element starts on a new line and takes up the full width of its container (by default).
It can have width, height, margin, and padding applied to all sides.
display: inline :
The element behaves like text, flowing along with other inline elements on the same line.
It does not respect width or height properties, and margins/paddings only work horizontally.
display: inline-block :
The element behaves like an inline element (appears on the same line), but it also respects
width and height properties.
Key Difference: inline-block combines the characteristics of both inline and block elements.
Higher z-index values will appear in front of elements with lower z-index values.
Elements with the same z-index value will be displayed in the order they appear in the HTML
(the one declared later will be in front).
Example:
282/411
css
div1 {
position: absolute;
z-index: 1;
}
div2 {
position: absolute;
z-index: 2;
}
Common uses:
However, it can cause layout issues, and modern layout techniques like Flexbox and CSS Grid are
recommended over using float .
Example:
css
img {
float: left;
margin-right: 15px;
}
This will make the image float to the left, allowing text to wrap around it.
283/411
The element is positioned relative to its normal position in the document flow.
You can move it using top , right , bottom , and left properties, but the space it originally
occupied in the document flow is still reserved.
2. position: absolute :
The element is positioned relative to the nearest positioned ancestor (not static ). If there is
no such ancestor, it is positioned relative to the initial containing block (usually the <html>
element).
It is removed from the document flow, meaning it does not take up space in the layout.
3. position: fixed :
The element is positioned relative to the viewport (the browser window), meaning it will stay in
the same place even when the page is scrolled.
Key Differences:
Relative: The element stays in the flow of the document but can be moved relative to its position.
Absolute: The element is removed from the flow and positioned relative to an ancestor.
Fixed: The element is removed from the flow and fixed to the viewport.
Here are the explanations for the meta viewport tag, CSS Flexbox, CSS Grid, and other related
concepts:
284/411
The meta viewport tag is used to control the layout of the webpage on mobile devices. It tells the
browser how to scale the content, allowing the page to be responsive and fit correctly on various
screen sizes.
Example:
html
width=device-width : Ensures the width of the page is equal to the width of the device screen.
initial-scale=1.0 : Sets the initial zoom level when the page is first loaded (1.0 means no zoom).
Without this tag, websites on mobile devices might appear zoomed out or not scale properly to the
screen width.
Example:
css
This media query applies the background color lightblue to the body if the viewport is 768px wide or
smaller (common for tablets and mobile devices).
Key conditions:
285/411
What is display: flex in CSS?
The display: flex property is used to create a flexible layout that distributes space along a row or
column, making it easier to align items within a container.
When you apply display: flex to a parent container, the children (flex items) are aligned in a flexible
way.
Key features:
Example:
css
.container {
display: flex;
justify-content: space-between;
}
This makes the items inside .container space out evenly across the container.
Key properties:
grid-template-columns and grid-template-rows : Define the number and size of the grid's
columns and rows.
grid-column and grid-row : Define how items span across columns or rows.
Example:
css
.container {
display: grid;
286/411
grid-template-columns: 1fr 2fr 1fr;
}
This creates a 3-column grid, with the second column being twice the size of the others.
You can create a sticky header with the position: sticky property, and it only works when the
element is within the scrollable content.
Example:
css
.header {
position: sticky;
top: 0;
background-color: #fff;
z-index: 100;
}
position: sticky keeps the element fixed once it reaches the top of the page.
What Are the 5 Best Practices for Creating a Responsive Design Using CSS?
1. Use a Fluid Grid Layout: Instead of fixed-width elements, use relative units like percentages or em
to create flexible, fluid layouts.
2. Use Media Queries: Apply different styles for different screen sizes to ensure your design looks
great on all devices.
3. Optimize for Mobile First: Start designing for smaller screens (mobile-first) and scale up to larger
screens using media queries.
Use max-width for desktop layouts, and min-width for mobile layouts.
287/411
4. Set the Viewport Properly: Always use the meta viewport tag to ensure your content scales
properly on mobile devices.
5. Use Flexbox and CSS Grid: These modern layout systems provide flexibility in designing
responsive layouts without using floats or positioning.
These practices will ensure your website is responsive and performs well across a variety of screen
sizes and devices.
288/411
Bootstrap is a popular front-end framework developed by Twitter. It is used to build responsive and
mobile-first websites and web applications. Bootstrap provides a collection of pre-built, customizable
components (e.g., buttons, forms, navigation bars) and a grid system for creating layouts. It helps
developers save time by avoiding the need to code from scratch and ensures that designs are
consistent across devices.
1. Foundation: Developed by Zurb, it's a responsive front-end framework with a strong emphasis on
customization and accessibility.
2. Bulma: A modern CSS framework based on Flexbox, with a clean design and simple syntax.
3. Tailwind CSS: A utility-first CSS framework that allows for easy customization using pre-defined
classes.
5. UIkit: A lightweight and modular front-end framework with customizable components and a
responsive grid system.
3. Grid System: Bootstrap includes a flexible 12-column grid system, making it easy to create
complex layouts that adjust to different screen sizes.
4. Cross-browser Compatibility: Bootstrap is compatible with all modern browsers (Chrome, Firefox,
Safari, Edge, etc.), ensuring consistent behavior across different environments.
5. Customization: Bootstrap is highly customizable with themes, and developers can override the
default styles to match their design preferences.
What are the 2 Ways to Include the Bootstrap Framework for Your Website?
1. Using CDN (Content Delivery Network):
You can link Bootstrap directly from a CDN, which is the easiest way. This method requires no
file downloading.
289/411
html
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js">
</script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js">
</script>
Download the Bootstrap files and include them in your project. This method gives you more
control over your assets.
html
Rows: Wrap the columns inside a .row container to create a horizontal group of columns.
Columns: Use classes like .col- , .col-sm- , .col-md- to define how many columns an element
should span, depending on the screen size.
Example:
html
<div class="row">
<div class="col-md-4">Column 1</div>
<div class="col-md-4">Column 2</div>
<div class="col-md-4">Column 3</div>
</div>
290/411
What is the Difference Between col-xs , col-sm , col-md , col-lg & col-xl ?
These classes represent different screen sizes and specify how columns behave at those breakpoints.
They are used to make your layout responsive and adjust to different screen sizes.
Example:
html
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-4">Column 1</div>
<div class="col-xs-12 col-sm-6 col-md-4">Column 2</div>
<div class="col-xs-12 col-sm-12 col-md-4">Column 3</div>
</div>
2. Cards: Flexible content containers with options for headers, footers, and content.
6. Forms: Pre-styled form controls like input fields, checkboxes, and radio buttons.
9. Tooltips: Small information boxes that appear when you hover over an element.
291/411
What is a Bootstrap Modal Component?
A Bootstrap modal is a dialog box that pops up over the current page. It is often used for notifications,
forms, or images that require user interaction. You can customize the modal content and appearance.
Example:
html
Example:
html
292/411
<button class="navbar-toggler" type="button" data-toggle="collapse" data-
target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle
navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
</ul>
</div>
</nav>
Example:
html
293/411
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExample" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a
IQ - Dynamic Routing
Understanding ActivatedRoute
04:51
IQ - ActivatedRoute
01:50
Query Parameters In Routing
04:17
IQ - Query Parameters In Routing
01:37
Navigating Routes
06:57
IQ - navigate() method
294/411
single page without reloading the entire page. Angular's @angular/router module allows for defining
different routes and provides navigation features like dynamic routing, nested routes, and query
parameters.
Example:
html
<a [routerLink]="['/home']">Home</a>
In this example, the user will be navigated to the "home" route when they click on the "Home" link.
Example:
html
<nav>
<ul>
<li><a [routerLink]="['/home']">Home</a></li>
<li><a [routerLink]="['/about']">About</a></li>
<li><a [routerLink]="['/contact']">Contact</a></li>
</ul>
</nav>
295/411
Example:
html
The component associated with the route will receive the productId parameter.
In the component:
typescript
ngOnInit() {
this.route.paramMap.subscribe(params => {
let productId = params.get('productId');
console.log(productId);
});
}
}
Example:
typescript
The ** is used for the wildcard route, and it captures all undefined paths.
296/411
Nested routes allow you to define routes within other routes, creating child routes for a parent
component. This is useful for layouts with sections or tabs.
Example:
typescript
In the parent component, you’ll have an <router-outlet> to load the child routes.
Redirecting Routes
In some cases, you may want to redirect the user to a different route.
Example:
typescript
The redirectTo parameter specifies the new route to navigate to, and pathMatch determines how
the route path is matched (e.g., 'full' matches the entire path).
Understanding ActivatedRoute
ActivatedRoute provides access to route parameters, query parameters, and other information
related to the currently active route.
Example:
typescript
297/411
import { ActivatedRoute } from '@angular/router';
ngOnInit() {
this.activatedRoute.params.subscribe(params => {
const id = params['id']; // Get route parameter 'id'
console.log(id);
});
}
}
html
typescript
ngOnInit() {
this.activatedRoute.queryParams.subscribe(params => {
const term = params['term'];
console.log(term);
});
}
}
298/411
Navigating Routes
You can programmatically navigate between routes using the Router service's navigate() method.
Example:
typescript
goToHome() {
this.router.navigate(['/home']);
}
}
The navigate() method allows you to specify the target route, either as a string or an array of path
segments.
IQ - Wildcard Routes
Wildcard routes are designed to catch all undefined routes and redirect users to a custom page,
typically a '404' error page. They are essential in handling any unknown routes gracefully.
Example:
typescript
This ensures that any route not matching a defined path will be redirected to the NotFoundComponent .
IQ - Redirecting Routes
Redirecting routes can be used to send users to a new path when they try to access a deprecated or old
route.
Example:
typescript
299/411
{ path: 'old', redirectTo: '/new', pathMatch: 'full' }
This redirect rule helps users transition seamlessly to new URLs without breaking links.
IQ - ActivatedRoute
ActivatedRoute provides essential information about the active route such as route parameters,
query parameters, and route configuration. It's often used in components to access route-specific data.
Example:
typescript
ngOnInit() {
this.route.snapshot.paramMap.get('id'); // Access route parameter
}
}
Example:
html
In the component:
typescript
300/411
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
this.activatedRoute.queryParams.subscribe(params => {
const page = params['page'];
const sortBy = params['sortBy'];
console.log(`Page: ${page}, SortBy: ${sortBy}`);
});
}
}
IQ - navigate() Method
The navigate() method allows for programmatic navigation between routes. It's commonly used
when actions like button clicks or form submissions should trigger a route change.
Example:
typescript
navigateToProfile() {
this.router.navigate(['/profile']);
}
}
This method is often used to implement navigation within complex applications without relying on
routerLink in templates.
301/411
Understanding JSON Pipe
01:58
Displaying Table Data To JSON string
Syntax:
html
{{ data | slice:start:end }}
end : (optional) The ending index (not inclusive). If omitted, the slice goes until the end of the array
or string.
Example:
html
html
<ul>
<li *ngFor="let item of items | slice:0:3">{{ item }}</li> <!-- Output: First 3 items -->
</ul>
html
<ul>
<li *ngFor="let item of items | slice:pageIndex:pageIndex+pageSize">{{ item }}</li>
302/411
</ul>
Here, pageIndex and pageSize control which items are displayed, and they change dynamically when
you move between pages.
For example:
typescript
goToNextPage() {
if (this.pageIndex + this.pageSize < this.items.length) {
this.pageIndex += this.pageSize;
}
}
goToPreviousPage() {
if (this.pageIndex - this.pageSize >= 0) {
this.pageIndex -= this.pageSize;
}
}
}
html
<ul>
<li *ngFor="let item of items | slice:pageIndex:pageIndex+pageSize">{{ item }}</li>
</ul>
<button (click)="goToPreviousPage()">Previous</button>
<button (click)="goToNextPage()">Next</button>
303/411
Understanding the Number Pipe
The Number Pipe is used to format a number according to a specific format. It allows you to specify
the number of decimal places, whether the number should be grouped by thousands, etc.
Syntax:
html
{{ value | number:'pattern' }}
Example:
html
Explanation:
Example:
html
This will display the weight in kilograms, rounded to two decimal places.
304/411
The JSON Pipe is used to display an object or an array as a JSON-formatted string.
Example:
html
This will convert the data object or array into a readable JSON string format and display it.
Example:
html
<table>
<tr *ngFor="let row of rows">
<td>{{ row | json }}</td>
</tr>
</table>
This will display each row in JSON format inside the table cells.
305/411
IQ - @ViewChild decorator
00:56
Property Decorators - Accessing The Projected Content With
@ContentChild
04:07
IQ - @ContentChild() Decorator
01:04
Property Decorators - Binding Properties With @HostBinding
04:16
Method Decorators - Binding Methods To Events With
@HostListener
05:07
Task - Implementing Color Picker
05:29
Parameter Decorators
@NgModule Decorator
Example of usage:
typescript
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
imports : Other modules whose exported classes are needed in this module.
@Component Decorator
306/411
The @Component decorator is used to define metadata for a component in Angular. It specifies
properties like the selector, template, and styles for the component.
Example of usage:
typescript
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular App';
}
@Input() Decorator
The @Input() decorator allows data to be passed from a parent component to a child component. It is
used to bind a value to a property in the child component.
Example of usage:
typescript
@Component({
selector: 'app-child',
template: `<h1>{{ childData }}</h1>`
})
export class ChildComponent {
@Input() childData: string = '';
}
307/411
In the parent component:
html
<app-child [childData]="parentData"></app-child>
You can use the @Input() decorator to pass data from a parent to a child component, creating
dynamic and reusable components. The example above demonstrates this flow.
@Output() Decorator
The @Output() decorator is used to create an event that allows the child component to communicate
with the parent component. It emits an event that the parent component can listen to.
Example of usage:
typescript
@Component({
selector: 'app-child',
template: `<button (click)="sendMessage()">Send Message</button>`
})
export class ChildComponent {
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit('Hello Parent!');
}
}
html
<app-child (messageEvent)="receiveMessage($event)"></app-child>
You can combine both @Input() and @Output() decorators to create communication between parent
and child components. This can be done by passing data to the child component with @Input() and
receiving events from the child with @Output() .
308/411
@ViewChild Decorator
The @ViewChild decorator is used to access a child component, directive, or DOM element in the
parent component class. It allows you to interact with the child component directly, access its
properties, and call methods.
Example:
typescript
@Component({
selector: 'app-parent',
template: `<app-child></app-child>`
})
export class ParentComponent {
@ViewChild(ChildComponent) child: ChildComponent;
ngAfterViewInit() {
console.log(this.child.someMethod());
}
}
@ContentChild Decorator
The @ContentChild() decorator is used to access projected content in a component. It allows you to
retrieve content that is inserted into the component via <ng-content> .
Example:
typescript
@Component({
selector: 'app-content-child',
template: '<ng-content></ng-content>'
})
export class ContentChildComponent {
@ContentChild('content') content: ElementRef;
ngAfterContentInit() {
console.log(this.content.nativeElement);
}
}
309/411
@HostBinding Decorator
The @HostBinding decorator is used to bind a property of the host element to a property of the
component. This can be useful for controlling styles, attributes, or properties directly from within the
component class.
Example:
typescript
@Component({
selector: 'app-host-binding',
template: `<p>Host Binding Example</p>`
})
export class HostBindingComponent {
@HostBinding('class.active') isActive = true;
}
@HostListener Decorator
The @HostListener decorator is used to listen for events on the host element and bind them to
methods in the component.
Example:
typescript
@Component({
selector: 'app-host-listener',
template: `<p>Host Listener Example</p>`
})
export class HostListenerComponent {
@HostListener('click', ['$event'])
onClick(event: MouseEvent) {
console.log('Element clicked', event);
}
}
310/411
In the task of implementing a color picker, you would typically use a form input field with type color ,
and bind it to a component's property using two-way data binding:
html
This allows users to pick a color, which will be reflected in the component.
Parameter Decorators
Parameter decorators are used to modify the behavior of method parameters. For example,
@Inject() is used to inject dependencies into a method parameter, while @Optional() is used to
mark a parameter as optional in dependency injection.
These decorators are typically used in service classes or component methods to configure
dependencies or behavior at runtime.
bash
2. Pipe implementation:
typescript
311/411
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sortNumbers'
})
export class SortNumbersPipe implements PipeTransform {
transform(value: number[], order: string = 'asc'): number[] {
if (!Array.isArray(value)) return value;
return value.sort((a, b) => (order === 'asc' ? a - b : b - a));
}
}
In the above example, the pipe sorts an array of numbers in ascending ( 'asc' ) or descending
( 'desc' ) order based on the input parameter order .
html
<ul>
<li *ngFor="let num of numbers | sortNumbers:'desc'">{{ num }}</li>
</ul>
bash
2. Pipe implementation:
typescript
@Pipe({
name: 'letterCount'
})
312/411
export class LetterCountPipe implements PipeTransform {
transform(value: string): number {
return value ? value.length : 0;
}
}
html
Pure pipes are those whose output depends only on the input values and will only re-execute
if the inputs to the pipe change. Angular executes pure pipes only when Angular detects a
change in the input data. They are efficient because Angular can cache their output when
inputs stay the same.
Impure Pipes:
Impure pipes are executed on every change detection cycle, even if the input data hasn't
changed. They are useful when dealing with objects like arrays or collections where the data
may change, but the reference of the object may not change.
You can make a pipe impure by setting the pure property to false in the pipe decorator.
typescript
@Pipe({
name: 'purePipe',
pure: true // This is the default behavior
})
export class PurePipe implements PipeTransform {
transform(value: string): string {
return value.toUpperCase();
}
}
313/411
Example of impure pipe:
typescript
@Pipe({
name: 'impurePipe',
pure: false // This makes it an impure pipe
})
export class ImpurePipe implements PipeTransform {
transform(value: any): any {
return value.map(item => item.toUpperCase());
}
}
However, using impure pipes can negatively impact performance, especially for large datasets. It's a
good practice to use them sparingly and only when necessary.
html
<ul>
<li *ngFor="let item of items | impurePipe">{{ item }}</li>
</ul>
In this case, impurePipe will be invoked on every change detection cycle, even if the array items
hasn't changed in terms of object reference.
In summary:
Pure pipes are efficient and only run when input data changes.
Impure pipes are less efficient because they run on every change detection cycle, but they are
necessary when the data structure can change without changing the reference.
314/411
Q - Introduction to Services
01:07
Dependency Injection
03:39
IQ - Dependency Injection
00:44
Providing Services
05:34
IQ - Providing Services
01:42
Injecting services using inject()
06:19
IQ - inject() function
bash
typescript
@Injectable({
providedIn: 'root' // This makes the service available globally
})
export class MyService {
constructor() { }
315/411
getGreeting(): string {
return "Hello from MyService!";
}
}
1. Providers: When you configure Angular to use a service, you are defining a provider that tells
Angular how to create and inject the service.
2. Injector: Angular has an injector that is responsible for instantiating and providing the correct
services when required.
typescript
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html'
})
export class MyComponent implements OnInit {
ngOnInit(): void {
console.log(this.myService.getGreeting());
}
}
Providing Services
316/411
In Angular, you can provide services in different ways:
1. At the Component Level: A service can be provided only to a component and its children by using
the providers array in the @Component decorator.
typescript
@Component({
selector: 'app-child',
providers: [MyService] // MyService is available only in this component and its
children
})
export class ChildComponent {
constructor(private myService: MyService) { }
}
2. At the Module Level: A service can be provided at the module level, making it available to all
components in that module.
typescript
@NgModule({
providers: [MyService] // MyService is available throughout this module
})
export class AppModule { }
3. Global Scope: You can make a service available globally by providing it in the root using
providedIn: 'root' in the @Injectable decorator. This makes the service available throughout
the application without needing to provide it in every component or module.
typescript
317/411
private myService = inject(MyService);
constructor() {
console.log(this.myService.getGreeting());
}
}
This approach works well with standalone components and functions in Angular, where traditional
constructor injection isn't available or appropriate.
Dependency Injection (DI) helps Angular manage the dependencies of components and services.
Providing Services can be done at the component, module, or global level using providedIn:
'root' .
These concepts allow for clean, modular, and testable code in Angular applications.
Injecting Tokens
04:25
IQ - Injecting tokens
01:33
Injecting String Tokens
02:23
IQ - Injecting String Tokens
00:42
Injection Token Object
02:44
IQ - Injection Token Object
00:57
Providing Value With useValue
02:12
IQ - Providing Value With useValue
00:35
Task - Provide A Constant Value As Dependency
02:44
Alias Provider - useExisting Property
02:13
318/411
IQ - useExisting Property
00:25
Factory Provider - useFactory Property
02:22
IQ - useFactory Property
01:16
Providing dependencies using “deps” property with useFactory
03:51
IQ - Providing dependencies using “deps” property with useFactory
00:59
useFactory Vs useValue
Angular's DI system works based on tokens, which are typically the class names. However, for non-
class types (like string literals, constants, or other objects), you need to create injection tokens.
Injection Token is defined using the InjectionToken class, which creates a unique token for
dependency injection.
typescript
@Injectable({
providedIn: 'root',
})
export class ApiService {
constructor(@Inject(API_URL) private apiUrl: string) {}
getData() {
console.log(`API URL: ${this.apiUrl}`);
}
}
typescript
@NgModule({
providers: [
319/411
{ provide: API_URL, useValue: 'https://api.example.com' }
]
})
export class AppModule { }
typescript
@Injectable({
providedIn: 'root',
})
export class TitleService {
constructor(@Inject(APP_TITLE) private title: string) {}
getTitle() {
return this.title;
}
}
typescript
@NgModule({
providers: [
{ provide: APP_TITLE, useValue: 'My Angular Application' }
]
})
export class AppModule { }
320/411
An Injection Token Object is typically used when you need to inject an object as a dependency. This is
especially useful for complex configuration settings.
Example:
typescript
@Injectable({
providedIn: 'root',
})
export class ConfigService {
constructor(@Inject(CONFIG_TOKEN) private config: Config) {}
getConfig() {
return this.config;
}
}
@NgModule({
providers: [
{ provide: CONFIG_TOKEN, useValue: { apiEndpoint: 'https://api.example.com',
enableLogging: true } }
]
})
export class AppModule { }
Example:
typescript
@NgModule({
providers: [
321/411
{ provide: API_URL, useValue: 'https://api.example.com' }
]
})
export class AppModule { }
This method is useful for values that don't change or are static.
Example:
typescript
@Injectable({
providedIn: 'root'
})
export class MyService {
getServiceName() {
return 'MyService';
}
}
@Injectable({
providedIn: 'root',
useExisting: MyService // Aliasing another service
})
export class AliasService {
constructor(private myService: MyService) {}
getServiceName() {
return this.myService.getServiceName();
}
}
322/411
With useFactory , Angular allows you to provide dependencies based on a factory function. This is
particularly useful when you need to dynamically decide how to provide a service or value based on
runtime conditions.
typescript
@NgModule({
providers: [
{ provide: ApiService, useFactory: apiServiceFactory }
]
})
export class AppModule { }
Example:
typescript
@NgModule({
providers: [
{ provide: MyService, useFactory: myFactory, deps: [API_URL] }
]
})
export class AppModule { }
In this case, the factory function receives the API_URL as a parameter from the DI system and creates
the service dynamically.
323/411
useFactory vs useValue
useFactory is used when you need to create a value or service dynamically based on certain
conditions or logic.
Example:
useFactory is more flexible and allows you to generate values or services on the fly, based on
runtime logic.
Both are essential for providing different kinds of dependencies and values in Angular's DI system.
In template-driven forms, the form controls are defined in the HTML template and are linked to the
Angular form model using directives. Template-driven forms are simple, declarative, and easy to
implement for basic form scenarios.
typescript
324/411
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // Import FormsModule
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, FormsModule], // Add FormsModule to imports
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {}
In your template, you can use the ngForm directive to initialize the form. It helps bind the form data
with the form controls, making it possible to track the validity and status of the form.
html
ngForm creates a form model to keep track of the state of the form.
IQ - ngForm directive
The ngForm directive is automatically applied to the form element in template-driven forms. It is
responsible for keeping track of the overall state of the form, such as whether it's valid or dirty, and for
managing its submission.
Binds form data with the UI and provides the form status (valid, dirty, etc.).
325/411
Automatically handles validation and submission.
html
Component class:
typescript
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
onSubmit(form: any) {
console.log(form.value); // Form data
}
onReset(form: any) {
form.reset(); // Reset form data
}
}
In this example:
The Submit button triggers the onSubmit() method when clicked, which logs the form data.
The Reset button triggers the onReset() method, which resets the form values.
326/411
Template Driven Form
In template-driven forms, you handle user input and validation directly in the template using directives
like ngModel , ngForm , and required . It is great for simpler forms with less complex logic. You don't
have to write much code in the component class, which makes it very easy to use for simple forms.
You want to work with Angular's form system declaratively (directly in the template).
You don't need extensive control over the form structure or behavior programmatically.
In such cases, template-driven forms are easy to implement and use, but for more complex forms or
dynamic form controls, reactive forms might be a better option.
Understanding ReactiveFormsModule
02:41
IQ - ReactiveFormsModule
00:54
Understanding FormControl
05:01
IQ - FormControl
01:16
Understanding FormGroup
05:50
IQ - Understanding FormGroup
01:28
Dynamic Forms With FormArray
05:40
IQ - Dynamic Forms With FormArray
01:22
Understanding FormBuilder
01:52
IQ - FormBuilder
00:37
Validating Form Controls
05:31
327/411
IQ - Validating Form Controls
00:31
Task - Creating Multi Step Reactive Form With Bootstrap (Part 1)
05:02
Task - Creating Multi Step Reactive Form With Bootstrap (Part 2)
03:56
Task - Creating Multi Step Reactive Form With Bootstrap (Part 3)
08:25
Tracking Form Control States
04:34
IQ - Tracking Form Control States
00:44
Task - Multiple Validations On Password Field
04:52
Creating Custom Validators
05:02
IQ - Creating Custom Validators
00:51
Task - Custom URL Validator
05:56
Securing Routes With Route Guards
06:05
IQ - Route Guards
01:12
CanDeactivate Route Guard
06:37
IQ - CanDeactivate Route Guard
00:49
CanActivateChild Route Guard
05:11
IQ - CanActivateChild Route Guard
00:24
Task - Login Authentication
07:21
CanMatch Guard
05:03
IQ - CanMatch Guard
01:03
Understanding ReactiveFormsModule
In Angular, Reactive Forms (also known as Model-Driven Forms) offer more control and flexibility over
the form logic than Template-Driven Forms. To use reactive forms in Angular, the
ReactiveFormsModule needs to be imported into your module.
328/411
3. Reactive forms are more scalable for complex forms because they offer explicit control over form
data and validation.
typescript
@NgModule({
imports: [ReactiveFormsModule],
// other properties
})
export class AppModule {}
IQ - ReactiveFormsModule
Reactive forms are ideal when you need:
Complex form scenarios such as conditional validation, complex logic, and asynchronous
operations.
A programmatic approach where form models are defined and controlled in the component.
Understanding FormControl
A FormControl represents an individual input element in a form. It tracks the value, validation, and
status of that input.
Example:
typescript
typescript
329/411
name.setValidators([Validators.required, Validators.minLength(3)]);
IQ - FormControl
A FormControl is primarily used for:
Applying validation and tracking the status (valid, invalid, dirty, touched).
Understanding FormGroup
A FormGroup is used to group multiple FormControl instances into a single object. It's typically used
to represent a logical group of related form controls.
Example:
typescript
A FormGroup also allows you to apply validation across multiple form controls and track their status
collectively.
IQ - Understanding FormGroup
A FormGroup is useful when:
You need to apply shared validation across multiple controls (e.g., both name and email fields
must be required).
330/411
You need to manage the state of a group of related inputs.
Example:
typescript
typescript
emails.push(new FormControl(''));
emails.removeAt(0);
You don't know in advance how many form controls you need (e.g., a dynamic list of items).
You want to perform operations like adding, removing, or updating form controls dynamically.
Understanding FormBuilder
The FormBuilder service is a convenience service provided by Angular to simplify the creation of form
controls, form groups, and form arrays. It helps reduce boilerplate code when defining reactive forms.
Example:
331/411
typescript
createForm() {
this.form = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
});
}
IQ - FormBuilder
FormBuilder is useful when:
You want to simplify the process of creating form controls and groups.
Example:
typescript
name.setValidators([Validators.required, Validators.minLength(3)]);
typescript
this.form.get('name').valid;
332/411
IQ - Validating Form Controls
Form controls are validated when:
Example steps:
3. Use the next and previous buttons to navigate between the steps.
This allows for a more user-friendly approach when dealing with large forms.
Example:
typescript
333/411
Providing feedback to users (e.g., showing error messages if a field is invalid).
Determining if the user has interacted with the form (e.g., marking a field as touched after focus
loss).
Example:
typescript
You can apply the custom validator to a form control like so:
typescript
this.form.get('name').setValidators([customValidator]);
You need to apply complex validation logic based on multiple fields or external conditions.
334/411
Handle actions before navigation like checking if the user is logged in.
IQ - Route Guards
Route guards help:
Prevent navigation when certain conditions aren't met (e.g., unsaved changes).
You want to warn users before they leave a page with unsaved changes.
You need to prompt users for confirmation before navigating away from the current route.
335/411
IQ - CanActivateChild Route Guard
This guard is useful when:
You want to ensure that access to nested routes is controlled by a parent route guard.
CanMatch Guard
The CanMatch guard can be used to determine if a route should be matched based on custom
conditions, such as user roles or permissions.
IQ - CanMatch Guard
The CanMatch guard is beneficial when:
You need to apply different matching strategies based on user roles, URL segments, or other
factors.
Understanding ReactiveFormsModule
In Angular, reactive forms allow you to work with forms in a more programmatic way, giving you more
control over form data, validation, and handling form states. To use reactive forms in Angular, you need
to import the ReactiveFormsModule into your application module.
1. Import ReactiveFormsModule:
typescript
336/411
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [ReactiveFormsModule],
// other properties
})
export class AppModule {}
2. Define the form model: You define the form controls and groups in the component class.
3. Bind the form model to HTML: You bind the form controls to your template using form control
directives.
Reactive forms are ideal when you need more control over the form's structure and logic, such as
dynamic validation or form arrays.
IQ - ReactiveFormsModule
Reactive forms are recommended when:
Dynamic forms: You need to create forms based on dynamic data (e.g., form arrays for repeated
fields).
Advanced validation logic: You require complex validation rules that can be applied
programmatically.
Fine-grained control: You want to programmatically interact with the form controls (e.g., changing
values, validation, etc.).
Understanding FormControl
A FormControl is a class in Angular's reactive form module that represents a single input field in a
form. It holds the value, status (valid, invalid), and validation errors of an individual form control.
Basic Usage:
typescript
337/411
const name = new FormControl('');
IQ - FormControl
A FormControl is a great choice when:
You want to manage the value, validation, and state of a single field without dealing with complex
groupings.
Understanding FormGroup
A FormGroup is used to group related form controls into a single unit. It represents a collection of
FormControl s and allows for managing validation and form state for multiple controls as a group.
Example of FormGroup:
typescript
In the example above, a FormGroup is created with two form controls, one for name and one for
email . You can perform validation on the entire group, and the status of the group will reflect the
validation of all controls.
338/411
IQ - Understanding FormGroup
A FormGroup is useful when:
You need to group related form fields together (e.g., a name, email, and phone fields).
You want to validate a set of controls together or disable/enable a set of controls based on a
condition.
You are working with multi-step forms where each step contains multiple form fields.
Example of FormArray:
typescript
You have an unknown number of form fields that need to be dynamically generated.
You want to enable the user to add/remove items from a list of controls.
339/411
Understanding FormBuilder
The FormBuilder service in Angular is a helper service to simplify the process of creating form controls
and groups. It eliminates the need to manually instantiate FormControl or FormGroup .
typescript
createForm() {
this.form = this.fb.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
});
}
In the example above, FormBuilder creates the FormGroup and FormControl for the name and
email fields with validation.
IQ - FormBuilder
FormBuilder is great when:
Built-in Validators:
340/411
typescript
this.form.get('name').setValidators([Validators.required, Validators.minLength(3)]);
Custom Validators:
typescript
2. Step Navigation: Use navigation buttons ( next and previous ) to allow users to move between
steps.
341/411
Common States:
touched: True if the user has focused on the control and then blurred it.
Example:
typescript
if (this.form.get('name').invalid) {
// Show error message
}
Enable/Disable Actions: You can enable or disable form submission based on the form’s validity
( this.form.valid ).
Feedback: Show validation messages when the form control state changes (e.g., error messages
when invalid).
typescript
342/411
Using Custom Validators:
typescript
this.form.get('username').setValidators([noSpaceValidator]);
You need validation logic that is not covered by Angular’s built-in validators.
You need to validate form controls based on complex conditions (e.g., multiple field comparisons
or external data).
CanDeactivate: Prevents users from leaving a route if there are unsaved changes.
IQ - Route Guards
Route guards are essential when:
You need to confirm a user’s actions before allowing them to leave a page (e.g., unsaved changes).
343/411
CanDeactivate Route Guard
A CanDeactivate guard helps prevent users from navigating away from a route when there are
unsaved changes, such as form data.
typescript
@Injectable({
providedIn: 'root'
})
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate): Observable<boolean> | Promise<boolean> |
boolean {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
You need to confirm navigation away from a page to prevent data loss.
344/411
01:29
Preloading Strategy (NoPreloading)
02:51
IQ - NoPreloading Strategy
00:28
Preloading Strategy (Custom Preloading)
06:01
IQ - Custom Preloading Strategy
01:30
Task - Preloading Based On User Roles
02:35
IQ - Preloading Vs. Lazy Loading
01:45
Deferred Loading
05:22
@defer with @placeholder
02:56
@defer with @loading
02:27
@defer with @error
01:27
Working with Triggers (on idle)
02:49
Working with Triggers (on viewport)
04:44
Working with Triggers (on interaction)
01:31
Working with Triggers (on hover)
02:01
Working with Triggers (on immediate)
01:07
Working with Triggers (on timer)
01:07
Prefetching of @defer blocks
02:05
Defining Custom Triggers
explain in detail with examples
345/411
Faster Initial Load: By loading only the essential parts of an app initially, lazy loading reduces the
time taken to load the app.
Better Performance: Resources like scripts and styles are loaded only when needed, saving
bandwidth and improving performance.
Separation of Concerns: Lazy loading enables a clear separation between modules in the app,
ensuring that only the required modules are loaded, rather than everything at once.
Example:
Let’s say you have a component called DashboardComponent and a module called DashboardModule .
Instead of loading the DashboardModule with the app’s initial load, you can lazy-load it when the user
navigates to the dashboard route.
typescript
@NgModule({
declarations: [DashboardComponent],
imports: [CommonModule],
})
export class DashboardModule {}
typescript
In this example, the DashboardModule is loaded lazily when the user navigates to the /dashboard
route.
346/411
Preloading of Components
Preloading is the process of loading modules in the background after the initial app load, but before
the user navigates to the route. It’s used to improve the user experience by loading modules that the
user may likely navigate to next, without waiting for the user to explicitly trigger the loading.
Preloading Strategy:
Angular provides a default no preloading strategy and the option for custom preloading strategies to
allow loading modules in the background.
typescript
This is useful when you want to save bandwidth and only load resources when requested by the user.
typescript
@Injectable({
providedIn: 'root'
347/411
})
export class CustomPreloadingStrategy implements PreloadingStrategy {
preload(route: Route, load: () => Observable<any>): Observable<any> {
// Preload if the route's data has a 'preload' flag
return route.data && route.data['preload'] ? load() : of(null);
}
}
typescript
typescript
With this setup, the DashboardModule will be preloaded in the background if the preload flag is
true .
typescript
@Injectable({
providedIn: 'root'
})
export class RoleBasedPreloadingStrategy implements PreloadingStrategy {
constructor(private authService: AuthService) {}
348/411
if (this.authService.isAdmin() && route.data['preloadForAdmin']) {
return load(); // Preload for admin users
}
return of(null); // Do not preload for other users
}
}
2. Routing Setup:
typescript
This ensures that admin-specific modules are preloaded while other modules are only loaded when
requested.
Preloading: Modules are loaded in the background, even before the user navigates to them.
Lazy loading helps reduce the initial load time, while preloading ensures that certain modules are
available without waiting when the user decides to navigate to them.
Deferred Loading
Deferred Loading refers to delaying the loading of resources (e.g., images, modules) until certain
conditions are met. This can be done by using placeholders or loading indicators until the resource is
ready.
349/411
@loading: A loading indicator that is displayed until the content is fully loaded.
Example:
html
In this example, the image will only load when it is needed, showing a loading placeholder initially, and
an error message if it fails to load.
1. Idle Trigger: Waits until the user is idle before triggering loading.
typescript
@defer onIdle
2. Viewport Trigger: Loads resources when they come into view in the viewport.
typescript
@defer onViewport
3. Interaction Trigger: Triggers loading when the user interacts with the page (e.g., clicks a button).
typescript
@defer onInteraction
4. Hover Trigger: Loads when the user hovers over a particular element.
typescript
@defer onHover
350/411
typescript
@defer onImmediate
typescript
@defer onTimer
typescript
@defer prefetch
This ensures that content that may be needed soon is fetched and ready before the user triggers the
loading.
typescript
@defer onCustomTrigger
For instance, you might want to load resources after the user has scrolled a certain distance down the
page. Custom triggers give you full flexibility in how and when to defer loading.
351/411
These techniques improve the user experience and application performance by delaying the loading of
non-essential resources until they are required, ensuring smoother and faster interactions.
An Observable is an object that represents a collection of future values or events. You can think of it as
a stream that emits values over time.
typescript
observable.subscribe(value => {
352/411
console.log(value); // Output: Hello World
});
In the above example, the Observable emits two values ( 'Hello' and 'World' ) and completes the
stream.
RxJS (Reactive Extensions for JavaScript) is a library for composing asynchronous and event-based
programs using Observables. It provides a set of operators like map , filter , merge , and many
others that help you manipulate and combine multiple Observables.
Managing Subscriptions:
When you subscribe to an Observable, you get a Subscription object. This object allows you to manage
and cancel the subscription (unsubscribe).
typescript
If you don't unsubscribe from an Observable, it can lead to memory leaks, as the subscription will
continue to emit values even after the component or service is destroyed.
Unsubscribing an Observable
353/411
Unsubscribing is important in Angular applications to avoid memory leaks. If a component subscribes
to an Observable, it’s necessary to unsubscribe when the component is destroyed.
Angular provides the ngOnDestroy lifecycle hook to clean up subscriptions when a component is
destroyed.
typescript
@Component({
selector: 'app-example',
template: `<div>Check console for output</div>`
})
export class ExampleComponent implements OnDestroy {
private subscription: Subscription;
ngOnInit() {
const observable = new Observable(observer => {
observer.next('Hello');
observer.next('World');
observer.complete();
});
ngOnDestroy() {
// Unsubscribe when the component is destroyed to prevent memory leaks
this.subscription.unsubscribe();
}
}
By calling unsubscribe() inside ngOnDestroy , you ensure that the subscription is properly cleaned up
when the component is removed from the DOM.
354/411
The async pipe is a powerful feature in Angular used to automatically subscribe and unsubscribe from
Observables in templates. It helps manage Observables without having to manually handle the
subscription and unsubscription in the component class.
html
typescript
@Component({
selector: 'app-example',
template: `<div>{{ observableData | async }}</div>`
})
export class ExampleComponent {
observableData: Observable<string>;
ngOnInit() {
this.observableData = of('Hello, Async Pipe!');
}
}
In this example:
The async pipe subscribes to this Observable, automatically updating the view when new values
are emitted.
Angular will handle the subscription and unsubscription for you when the component is destroyed,
so you don't need to manually unsubscribe.
2. Simplified Code: Reduces the need to manually manage subscriptions, making your code cleaner
and less error-prone.
355/411
Task - Fetching JSON Data With Async Pipe
Fetching data from an API and displaying it in the template using the async pipe is one of the most
common use cases.
typescript
@Component({
selector: 'app-data-fetch',
template: `
<ul>
<li *ngFor="let item of data$ | async">{{ item.name }}</li>
</ul>
`
})
export class DataFetchComponent implements OnInit {
data$: Observable<any>;
ngOnInit() {
this.data$ = this.http.get<any[]>('https://api.example.com/data');
}
}
In this example:
The data is bound to the template using the async pipe, which automatically subscribes and
updates the view when the data is loaded.
Cold Observable:
A Cold Observable starts emitting values only when it is subscribed to. Each subscriber gets a separate
execution and independent stream of data. This is ideal for HTTP requests or scenarios where each
356/411
subscriber needs a fresh, separate stream of data.
Example: HTTP requests are Cold Observables. When multiple components subscribe to the same
HTTP request, each component gets a fresh response.
typescript
Here, each subscription triggers the Observable to emit the same values independently.
Hot Observable:
A Hot Observable emits values regardless of whether there are subscribers or not. When a subscriber
joins, it starts receiving the values that have been emitted so far. It is shared between multiple
subscribers, meaning they get the same set of emitted values. Event listeners, WebSocket
connections, and Subject-based Observables are examples of Hot Observables.
Example: A Subject is a Hot Observable. It can multicast values to multiple subscribers without
re-executing the source stream.
typescript
hotObservable.next('Hello');
hotObservable.next('World');
In this case, both subscribers will receive the same emissions ( 'Hello' and 'World' ), but the
emissions happen independently of the subscriptions.
Summary
Observables are used to represent asynchronous data streams.
357/411
RxJS provides operators to manipulate Observables (e.g., map , filter , merge ).
Async pipe automatically subscribes to and unsubscribes from Observables in Angular templates.
Hot Observables are shared and emit values even if there are no subscribers.
Cold Observables emit values only when subscribed to and provide fresh data to each subscriber.
This fundamental understanding of Observables and RxJS is critical for building reactive, scalable
Angular applications.
RxJS { of } Operator
02:58
IQ - RxJS { of } Operator
00:23
RxJS { from } Operator
01:56
IQ - RxJS { from } Operator
00:59
RxJS { interval } Operator
03:11
RxJS { timer } Operator
03:43
Task - Implementing a loading spinner
03:07
RxJS { EMPTY } Operator
02:38
IQ - RxJS { EMPTY } Operator
00:57
RxJS Pipeable Operators
03:00
IQ - RxJS Pipeable Operators
01:10
RxJS { filter } Operator
03:32
RxJS { map } Operator
04:43
IQ - RxJS { map } Operator
00:44
RxJS { mergeMap } Operator
02:38
IQ - RxJS { mergeMap } Operator
01:17
Task - Displaying the Products Associated With User
02:42
RxJS { concatMap } Operator
03:56
IQ - concatMap() operator
358/411
01:06
RxJS { switchMap } Operator
04:13
IQ - RxJS { switchMap } Operator
explain in detail with examples
1. of Operator
The of operator is used to create an Observable that emits a sequence of values (either from a single
value or an array of values) immediately when subscribed.
Example:
typescript
observable.subscribe(value => {
console.log(value); // Output: 1, 2, 3, 4
});
Explanation:
The of operator immediately emits the values 1, 2, 3, 4 in order when the subscription
happens.
2. from Operator
The from operator is used to convert different types of data structures into an Observable. It can take
an array, a promise, or an iterable, and emit the values of that structure as a sequence.
Example:
359/411
typescript
observable.subscribe(value => {
console.log(value); // Output: 1, 2, 3, 4
});
Explanation:
The from operator converts an array into an Observable and emits each value in the array
sequentially.
3. interval Operator
The interval operator creates an Observable that emits increasing numbers starting from 0 at a
specified interval, indefinitely.
Example:
typescript
observable.subscribe(value => {
console.log(value); // Output: 0, 1, 2, 3, 4, ...
});
Explanation:
The interval operator emits an increasing sequence of integers starting from 0 at a fixed interval
of 1 second (1000 milliseconds).
4. timer Operator
The timer operator creates an Observable that waits for a specified delay before emitting a single
value or multiple values at regular intervals.
360/411
Example:
typescript
const observable = timer(2000, 1000); // First value after 2 seconds, subsequent values every
1 second
observable.subscribe(value => {
console.log(value); // Output: 0, 1, 2, 3, ...
});
Explanation:
The timer operator emits a value after an initial delay of 2 seconds and then continues to emit
values every second thereafter.
5. EMPTY Operator
The EMPTY operator creates an Observable that immediately completes without emitting any values.
Example:
typescript
observable.subscribe({
next: value => console.log(value), // Nothing will be logged
complete: () => console.log('Completed!') // Output: 'Completed!'
});
Explanation:
The EMPTY operator doesn't emit any values but immediately completes the Observable stream.
361/411
Pipeable operators are operators that can be chained using the pipe() method on an Observable.
They are used to transform, filter, or manage the data emitted by the Observable.
Example:
typescript
observable.subscribe(value => {
console.log(value); // Output: 4, 8
});
Explanation:
7. filter Operator
The filter operator is used to filter the emitted values based on a condition, similar to the JavaScript
Array.filter() method.
Example:
typescript
observable.subscribe(value => {
362/411
console.log(value); // Output: 2, 4
});
Explanation:
The filter operator only passes through even numbers (i.e., 2, 4).
8. map Operator
The map operator is used to transform the emitted values by applying a given function.
Example:
typescript
observable.subscribe(value => {
console.log(value); // Output: 2, 4, 6
});
Explanation:
9. mergeMap Operator
The mergeMap operator is used to transform each value emitted by the source Observable into a new
Observable and merge the results into one Observable. The result is emitted as a combined stream.
Example:
typescript
363/411
mergeMap(value => of(value * 2))
);
observable.subscribe(value => {
console.log(value); // Output: 2, 4, 6
});
Explanation:
The mergeMap operator takes each value from the source Observable and transforms it into a new
Observable (which is of(value * 2) in this case). It then merges the resulting Observables into
one stream.
Example:
typescript
observable.subscribe(value => {
console.log(value); // Output: 2, 4, 6
});
Explanation:
Unlike mergeMap , concatMap ensures that the values are emitted sequentially (one after another),
waiting for the completion of the current Observable before starting the next one.
364/411
The switchMap operator is used to switch to a new Observable based on each value emitted by the
source Observable, canceling the previous subscription if a new value arrives.
Example:
typescript
observable.subscribe(value => {
console.log(value); // Output: 2, 4, 6
});
Explanation:
The switchMap operator maps each emitted value to a new Observable and unsubscribes from
the previous one as soon as a new value arrives.
typescript
observable.subscribe(value => {
console.log(value); // Output: Data loaded
});
365/411
Explanation:
When the Observable is subscribed, it first emits 'Loading...' and shows the spinner.
After the switchMap operator switches to the fetchData() Observable (which simulates a delay),
the spinner is hidden once the data is loaded.
Conclusion
RxJS operators like of , from , interval , map , filter , mergeMap , switchMap , and others are
essential for creating and managing asynchronous streams in Angular applications. They allow you to
transform, filter, and combine data streams efficiently.
By using these operators, you can handle complex asynchronous workflows in a concise and readable
manner, avoiding callback hell and managing concurrency more effectively.
366/411
1. Making HTTP Calls with HttpClient
To make HTTP requests, you need to import the HttpClientModule and inject HttpClient into your
component or service.
Example:
typescript
@NgModule({
imports: [HttpClientModule],
})
export class AppModule {}
typescript
@Injectable({
providedIn: 'root',
})
export class ProductService {
private apiUrl = 'https://api.example.com/products'; // Sample API URL
getProducts(): Observable<any> {
return this.http.get(this.apiUrl); // GET request to fetch data
}
}
The getProducts method performs an HTTP GET request to fetch data from the backend API.
367/411
2. Making HTTP Calls with Observable
The HttpClient methods return an Observable, which means you can subscribe to the HTTP call to
get the response.
Example:
typescript
this.productService.getProducts().subscribe((data) => {
console.log(data); // Handle the fetched data here
});
In this example:
We subscribe to the getProducts method, and once the data is returned, we handle it inside the
subscribe() method.
Example:
typescript
To use this method, you would typically call it from your component:
typescript
In this example:
addProduct sends a POST request with a product object as the request body.
The server will process the request and return a response (usually the created object or a success
message).
368/411
4. Modifying Data with PUT Request
A PUT request is used to update an existing resource on the server.
Example:
typescript
typescript
In this example:
Example:
typescript
typescript
this.productService.deleteProduct(1).subscribe(response => {
console.log(response); // Handle the response from the DELETE request
369/411
});
In this example:
deleteProduct sends a DELETE request to remove a product from the backend server by its id .
Component Setup:
typescript
@Component({
selector: 'app-product-list',
templateUrl: './product-list.component.html',
})
export class ProductListComponent implements OnInit {
products: any[] = [];
ngOnInit() {
this.productService.getProducts().subscribe((data) => {
this.products = data;
});
}
}
Here:
The ProductListComponent retrieves the list of products when the component initializes
( ngOnInit ).
It uses the getProducts method from the ProductService to make the HTTP GET request.
370/411
In this part of the task, you'll allow users to add products using the POST request.
Component Setup:
typescript
@Component({
selector: 'app-product-add',
templateUrl: './product-add.component.html',
})
export class ProductAddComponent {
newProduct = { name: '', price: 0 };
addProduct() {
this.productService.addProduct(this.newProduct).subscribe((response) => {
console.log('Product added:', response);
});
}
}
In this example:
Upon form submission, the addProduct method sends a POST request to the backend to add the
new product.
Component Setup:
typescript
@Component({
selector: 'app-product-edit',
371/411
templateUrl: './product-edit.component.html',
})
export class ProductEditComponent implements OnInit {
product: any = { name: '', price: 0 };
constructor(
private productService: ProductService,
private route: ActivatedRoute
) {}
ngOnInit() {
const id = this.route.snapshot.paramMap.get('id');
this.productService.getProductById(id).subscribe((data) => {
this.product = data;
});
}
}
Here:
ProductEditComponent fetches the existing product data before allowing the user to edit it.
It uses the getProductById method from the service to fetch the product data by its id .
Component Setup:
typescript
updateProduct() {
this.productService.updateProduct(this.product.id, this.product).subscribe((response) => {
console.log('Product updated:', response);
});
}
This method sends a PUT request to update the product on the server.
10. Task - CRUD App - Deleting Products with DELETE Request (Part 5)
372/411
Lastly, you'll implement the feature to delete a product using the DELETE request.
Component Setup:
typescript
deleteProduct(id: number) {
this.productService.deleteProduct(id).subscribe((response) => {
console.log('Product deleted:', response);
});
}
The deleteProduct method will send a DELETE request to the server to remove the product by its id .
Conclusion
GET: Retrieves data from the server.
By implementing these methods using Angular’s HttpClient , you can build robust CRUD applications
that interact with backend services seamlessly.
Introduction to Signals
01:59
Creating Signal
03:44
IQ - Creating Signal
01:05
Updating Signal Value
03:10
IQ - update() method
01:30
Task - To-do List
07:45
Computed Signals
04:13
IQ - Computed Signals
01:35
Understanding effect() function
04:55
373/411
Cleaning up the effect()
05:15
Untracking Signals
05:07
Task - Updating The Cart using Signals
07:31
Linked Signals
04:53
Converting Observable To Signal
03:53
Task - Filtering Products Based on User Input with linkedSignal()
Let’s dive into the concepts related to Signals, including their creation, updates, and common use cases
such as tasks or to-do lists.
1. Creating a Signal
A Signal can be created to store reactive values, similar to variables in traditional programming but
with the ability to trigger updates when changed.
Example:
typescript
374/411
Example:
typescript
In this example:
update() is used to modify the signal value. The provided function receives the current value of
the signal and updates it.
Example:
typescript
Here:
addTodo() and removeTodo() methods update the signal when a task is added or removed.
4. Computed Signals
Computed Signals are signals that derive their value from other signals. They automatically update
when the signals they depend on change.
375/411
Example:
typescript
In this example:
Example:
typescript
effect(() => {
console.log('Signal value changed:', countSignal());
});
Here:
Example:
376/411
typescript
Here:
The cleanup function is called to stop the effect after a specific period or condition.
7. Untracking Signals
Untracking a signal means that you stop tracking its changes. This is useful when you no longer need
to react to changes in the signal.
Example:
typescript
untrack(() => {
console.log('This will not react to countSignal changes');
});
In this example:
untrack() prevents the code inside from reacting to changes in the signal value.
Example:
377/411
typescript
Here:
9. Linked Signals
Linked signals are signals that depend on each other. When one signal changes, it automatically
updates another signal.
Example:
typescript
In this example:
378/411
10. Converting Observable to Signal
Sometimes, you may want to convert an Observable to a Signal to work with reactive states in Angular.
Example:
typescript
In this example:
Example:
typescript
Here:
searchTermSignal changes.
379/411
Conclusion
Signals in Angular are powerful tools for managing state reactively. They help in building highly
responsive applications by automatically updating components when the underlying state changes.
From simple use cases like managing to-do lists or shopping carts, to more complex scenarios like
filtering and linked signals, Signals provide a clean and efficient way to handle state in modern Angular
applications.
1. CSR (Client-Side Rendering): In CSR, the browser loads a minimal HTML page, and JavaScript is
responsible for rendering the content dynamically. This is common in Single Page Applications
(SPA), where the page doesn't reload, and content updates based on user interaction. The first
page load might take longer, but subsequent page transitions are fast because only necessary data
is fetched and updated.
2. SSR (Server-Side Rendering): SSR is where the server generates the full HTML for a page on each
request, which is then sent to the client. This allows the browser to render the page immediately,
380/411
making it SEO-friendly and faster for the first render. After the initial load, it can switch to a more
interactive SPA-like behavior.
3. SSG (Static Site Generation): SSG is a method of pre-rendering the HTML at build time. This means
HTML files are generated for each page and stored on the server before the user requests them.
It’s great for websites with static content that doesn't change often, ensuring fast load times and
better SEO.
Setting up environment variables: Define configurations, API URLs, and other settings needed for
production.
Minifying the code: Compress the JavaScript, CSS, and other assets to reduce load times.
Bundling the assets: Group all JavaScript and CSS into smaller files to make delivery faster.
Setting up the server: Ensure that the correct software is running on the server (e.g., web server,
Node.js server for SSR, etc.).
The advantage of SPA is faster subsequent page loads, as the app doesn't need to reload the entire
page. However, the initial load might take a bit longer due to the JavaScript files and other
resources that need to be fetched.
SPA Deployment
For SPA deployment, the entire application is bundled and deployed as static files (HTML, CSS, JS)
on a server or CDN.
381/411
In production, a server (e.g., Node.js) might serve the SPA or directly serve static files with minimal
backend logic.
1. Build the project: Use the Angular CLI or other tools to bundle your app.
2. Deploy the static assets: Host the files on a web server or CDN.
3. Routing configuration: Ensure that the routing is handled properly using pathLocationStrategy
to avoid 404 errors for direct URLs.
1. Configuring server-side rendering: Using frameworks like Angular Universal (for Angular apps),
which allows rendering pages on the server before sending them to the browser.
2. Handling dynamic content: Content that changes based on user input must be rendered on the
server, and the data must be fetched server-side before the page is sent to the browser.
3. SEO considerations: Since SSR pre-renders pages, it allows search engines to index the content
better, providing a significant SEO benefit.
2. Modify the app to use server-side rendering strategies for routing and content.
3. Ensure the API calls are correctly handled server-side before the page is rendered.
3. Create server files (e.g., server.ts or app.server.module.ts ) to handle the SSR logic.
382/411
Optimizing Code for Server-Side Rendering (SSR)
To optimize your app for SSR:
1. Lazy Loading: Implement lazy loading of modules to reduce the amount of JavaScript that needs
to be initially loaded.
2. Avoid window/document references: Since the server doesn’t have access to the browser’s
window or document , any code that relies on them should be handled differently or only run on
the client.
3. Pre-fetching Data: Pre-fetch or pre-load critical data on the server to ensure that the page loads
faster.
Advantages of SSG:
Speed: Since the HTML is pre-rendered, the pages load incredibly fast.
SEO: Search engines can easily crawl static pages, improving SEO.
Cost: Since the pages are static, they can be hosted on simple file servers or CDNs at a low cost.
Implementing SSG
To implement SSG, you would:
1. Generate static pages for each URL of your site at build time (using tools like Next.js, Gatsby, or
Angular Static Generator).
2. Serve static assets through a CDN to ensure faster delivery and better global reach.
3. Ensure that any content that needs to be dynamically updated (e.g., user comments, login state) is
handled via client-side JavaScript.
383/411
Understanding Hybrid Rendering
Hybrid Rendering combines CSR, SSR, and SSG to use the right approach based on the needs of
specific pages in your app. For instance, you might use SSR for critical SEO pages, SSG for static
content, and CSR for highly interactive features.
Example:
SSR might be used for the homepage, product pages, and blog posts (for SEO benefits).
SSG could be used for a documentation site, where the content is rarely updated.
CSR would be used for user-specific pages like the dashboard, where content is highly interactive
and frequently changing.
Conclusion
Each rendering method—CSR, SSR, and SSG—has its own advantages, and choosing the right one
depends on your specific needs, such as performance, SEO, and user experience. Migrating from CSR
to SSR or implementing SSG requires understanding your app's requirements and optimizing code
accordingly. Hybrid rendering provides a flexible approach, allowing you to leverage the best of each
rendering strategy.
Let's break down each concept in detail with examples to help you understand them better.
1. CSR (Client-Side Rendering): The entire page (HTML, CSS, JS) is loaded initially, and then JavaScript
is used to render or update the content dynamically. This is common for Single Page Applications
(SPA) where the browser loads a minimal HTML page and dynamically updates the content as the
user interacts with the app.
2. SSR (Server-Side Rendering): The server generates the HTML content of the page and sends it to
the browser. This makes the page ready to be displayed immediately, which improves the SEO
(since the content is available on the server-side) and is beneficial for the first-time page load
performance.
3. SSG (Static Site Generation): Pages are pre-built at build time, and the generated HTML is served
to the client. It’s great for websites where content doesn’t change often (e.g., blogs or
documentation). It allows fast loading times and excellent SEO.
384/411
CSR Example
Let’s start with a simple Angular component that shows a list of users, which can be fetched using
Client-Side Rendering.
ts
// user-list.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-user-list',
template: `
<h2>User List</h2>
<ul>
<li *ngFor="let user of users">{{ user.name }}</li>
</ul>
`
})
export class UserListComponent implements OnInit {
users: any[] = [];
ngOnInit() {
// Fetch data from API on client-side
this.http.get('https://jsonplaceholder.typicode.com/users')
.subscribe((data: any[]) => {
this.users = data;
});
}
}
Explanation: The list of users is fetched on the client-side when the component is initialized
( ngOnInit ). The page will display a loading spinner initially until the data is loaded.
Note: CSR has a slight delay in the first page load, but once loaded, it’s faster as only data is
fetched in subsequent requests.
385/411
In Angular Universal (SSR), the initial rendering of the page happens on the server. The page is served
to the browser with pre-rendered HTML, improving the first-page load performance and SEO.
1. Setting up Angular Universal: Run the following command to add Angular Universal to your
existing Angular project:
bash
ng add @nguniversal/express-engine
ts
@NgModule({
imports: [AppModule, ServerModule],
bootstrap: [AppComponent]
})
export class AppServerModule {}
Now, after building the app ( ng build --prod && ng run your-project-name:server ), your Angular
app will be rendered on the server. When you visit a page, the server will send pre-rendered HTML to
the browser.
Explanation: The server sends fully-rendered HTML to the browser, improving SEO and initial page
load performance. After the initial load, the app behaves like a typical Angular SPA.
386/411
1. Set up a page that will use SSG:
js
// pages/index.js
import React from 'react';
return {
props: {
users
}
};
}
Explanation: The getStaticProps function runs at build time and fetches the list of users. These
users are then passed to the component as props, and the static HTML is generated during the
build process.
Note: This is Static Site Generation (SSG), where the HTML is generated once at build time. The
pages are fast because they are served as static files.
387/411
Hybrid Rendering Example
Hybrid Rendering is a combination of CSR, SSR, and SSG. For example, a website could use SSR for the
homepage (to get fast first load and SEO benefits), SSG for the blog (since the blog doesn't change
frequently), and CSR for the dashboard (since it's highly interactive and personalized).
In an Angular Universal app, you could use SSR for SEO-friendly pages and CSR for user-specific
content (like a dashboard).
CSR: Used for personalized, dynamic content (e.g., a user dashboard or admin panel).
1. Lazy Loading: Load modules only when required (e.g., when navigating to a specific route).
ts
// In app-routing.module.ts
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'products', loadChildren: () => import('./products/products.module').then(m =>
m.ProductsModule) }
];
2. Preloading: You can preload modules after the initial app load to improve navigation speed.
ts
// In app-routing.module.ts
const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'products', loadChildren: () => import('./products/products.module').then(m =>
m.ProductsModule) }
];
388/411
@NgModule({
imports: [RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })],
exports: [RouterModule]
})
export class AppRoutingModule {}
Explanation: The PreloadAllModules strategy will preload all lazy-loaded modules in the
background after the app is initially loaded.
SSR (Server-Side Rendering) provides better SEO and faster initial load times, but it can be more
complex to set up.
SSG (Static Site Generation) generates static HTML at build time, making it ideal for content that
doesn’t change often.
Hybrid Rendering uses a combination of CSR, SSR, and SSG to maximize performance and SEO.
Lazy Loading helps you load only the parts of the app that are needed, improving the
performance of large applications.
389/411
Manual Change Detection - RxJS Subjects
05:44
Using Async Pipe with BehaviorSubject
02:27
Implementing Zoneless Change Detection
explain in detail with examples
Angular checks for changes in the model (component data) and updates the view accordingly. When
something changes in the application (e.g., user interaction, API call), Angular checks whether the view
needs to be updated to reflect the new state of the model.
For example:
ts
In this case, Angular will throw an expression error because the user object is undefined when
Angular tries to read user.name .
Solution: To avoid expression errors, you can use safe navigation ( ?. ) to ensure that the object exists
before accessing its properties:
html
390/411
<!-- Safely access user.name -->
<p>{{ user?.name }}</p>
1. OnPush Change Detection Strategy: This strategy tells Angular to check for changes only when
specific conditions are met, reducing the number of checks performed.
2. Manual Change Detection: This allows you to manually trigger change detection only when
necessary.
3. Use of trackBy in ngFor: When rendering lists, using trackBy helps Angular optimize rendering
by only updating the items that have changed.
The component’s inputs change (e.g., a new value is passed into the component).
Example:
ts
@Component({
selector: 'app-user',
template: `{{ user.name }}`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserComponent {
391/411
@Input() user: { name: string };
}
With OnPush change detection, Angular will only recheck the UserComponent if the user input
changes (or if any other conditions like events occur).
ts
@Component({
selector: 'app-child',
template: `{{ data }}`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
@Input() data: string;
}
@Component({
selector: 'app-parent',
template: `<app-child [data]="parentData"></app-child>`
})
export class ParentComponent {
parentData = 'Initial Data';
updateData() {
this.parentData = 'Updated Data'; // This triggers change detection for ChildComponent
}
}
In this example:
The ChildComponent will only detect changes when the parentData changes.
392/411
With OnPush and Signals (as discussed in a previous part about signals in Angular), components can
share data in an efficient way. When using signals, you can ensure that changes are detected only
when necessary by associating signals with a component's input properties.
ts
@Component({
selector: 'app-user',
template: `{{ signal.value }}`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserComponent {
signal = signal('Hello World');
}
In this case, signal.value will be tracked for changes. If signal.value changes, the component will
be updated, as OnPush only triggers change detection when a relevant change occurs.
To solve this problem, you may need to manually trigger change detection in the parent component or
use Angular services to propagate changes across components.
ts
@Component({
selector: 'app-parent',
template: `<app-child [data]="data$ | async"></app-child>`
})
export class ParentComponent {
393/411
private dataSubject = new BehaviorSubject<string>('Initial Value');
data$ = this.dataSubject.asObservable();
changeData() {
this.dataSubject.next('Updated Value');
}
}
@Component({
selector: 'app-child',
template: `{{ data }}`
})
export class ChildComponent {
@Input() data: string;
}
In this case:
When the parent component calls changeData() , the BehaviorSubject emits a new value, and
the child component receives the updated data.
ts
@Component({
selector: 'app-parent',
template: `<app-child [data]="data$ | async"></app-child>`
})
export class ParentComponent {
private dataSubject = new BehaviorSubject<string>('Initial Value');
data$ = this.dataSubject.asObservable();
changeData() {
this.dataSubject.next('Updated Value');
}
}
394/411
In the above example:
Whenever the BehaviorSubject emits a new value, Angular updates the view with the latest value.
In a Zoneless application, you manage the change detection process manually, without relying on
Angular's zone. You can use RxJS or ChangeDetectorRef to handle manual triggering of change
detection.
ts
@Component({
selector: 'app-example',
template: `<p>{{ value }}</p>`
})
export class ExampleComponent {
value = 'Hello World';
triggerChangeDetection() {
this.value = 'Updated Value';
this.cdRef.detectChanges(); // Manually trigger change detection
}
}
In this example, after changing the value , we manually trigger change detection using
cdRef.detectChanges() . This is useful when you don't want to rely on Angular's zones for
performance reasons.
Summary of Concepts:
1. Change Detection is how Angular keeps track of the state of the application and updates the DOM
accordingly.
395/411
2. Expression errors happen when Angular tries to evaluate an expression that’s either undefined or
doesn’t exist.
3. OnPush change detection strategy optimizes performance by checking only when inputs change,
events are triggered, or observables emit.
4. Manual Change Detection with RxJS allows you to explicitly control when Angular should update
the view.
6. Zoneless Change Detection is a performance optimization technique where you manually trigger
change detection without Angular's NgZone.
These techniques can be combined depending on the complexity of the application and the
performance optimizations you need.
396/411
Q17. What is Hoisting in JavaScript?
01:49
Q18. What is Error Handling in JS?
01:16
Q19. What is JSON?
01:00
Q20. What is asynchronous programming in JS? What is its use?
03:27
Variables & Datatypes - Introduction
00:40
Q21. What are variables? What is the difference between var, let,
and const ?
03:32
Q22. What are data types in JS?
01:23
Q23. What is the difference between primitive and non-primitive
data types?
04:07
Q24. What is the difference between null and undefined in JS?
02:22
Q25. What is the use of typeof operator?
01:16
Q26. What is type coercion in JS?
01:41
Operators & Conditions - Introduction
00:34
Q27. What are operators? What are the types of operators in JS?
03:46
Q28. What is the difference between unary, binary, and ternary
operators?
01:33
Q29. What is short-circuit evaluation in JS?
02:16
Q30. What is operator precedence?
00:54
Q31. What are the types of conditions statements in JS?
03:19
Q32. When to use which type of conditions statements in real
applications?
03:32
Q33. What is the difference between == and ===?
01:46
Q34. What is the difference between Spread and Rest operator in
JS?
03:26
Arrays - Introduction
397/411
00:46
Q35. What are Arrays in JS? How to get, add & remove elements
from arrays?
02:59
Q36. What is the indexOf() method of an Array?
00:48
Q37. What is the difference between find() and filter() methods of
an Array?
03:02
Q38. What is the slice() method of an Array?
01:16
Q39. What is the difference between push() and concat () methods
of an Array ?
01:27
Q40. What is the difference between pop() and shift() methods of
an Array?
01:22
Q41. What is the splice() method of an Array?
03:27
Q42. Difference between the slice() and splice() methods of an
Array?
00:40
Q43. What is the difference map() and for Each() array methods of
an Array?
02:37
Q44. How to sort and reverse an array?
00:51
Q45. What is Array Destructuring in JS?
01:38
Q46. What are array-like objects In JS?
02:52
Q47. How to convert an array-like object into an array?
01:33
Loops - Introduction
00:35
Q48. What is a loop? What are the types of loops in JS?
01:25
Q49. What is the difference between while and for loops?
02:13
Q50. What is the difference between while and do-while loops?
01:50
Q51. What is the difference between break and continue
statement?
01:35
Q52. What is the difference between for and for…of loop in JS?
01:32
398/411
Q53. What is the difference between for…of and for…in loop?
01:28
Q54. What is forEach method? Compare it with for…of and for…in
loop?
02:32
Q55. When to use for…of loop and when to use forEach method in
applications?
01:39
Functions - Introduction
00:37
Q56. What are Functions in JS? What are the types of function?
01:26
Q57. Difference between named and anonymous functions?
01:48
Q58. What is function expression in JS?
01:11
Q59. What are Arrow Functions in JS? What is it use?
02:14
Q60. What are Callback Functions? What is it use?
02:26
Q61. What is Higher-order function In JS?
02:14
Q62. What is the difference between arguments and parameters?
00:44
Q63. In how many ways can you pass arguments to a function?
01:42
Q64. How do you use default parameters in a function?
00:56
Q65. What is the use of event handling in JS?
02:40
Q66. What are First-Class functions in JS?
01:25
Q67. What are Pure and Impure functions in JS?
02:57
Q68. What is Function Currying in JS?
02:34
Q69. What are call, apply and bind methods in JS?
02:34
Strings - Introduction
00:25
Q70. What is a String?
00:19
Q71. What are template literals and string interpolation in strings?
01:31
Q72. Difference between single quotes (''), double quotes ("") &
backticks('') ?
399/411
00:37
Q73. What are some important string operations in JS?
02:10
Q74. What is string immutability?
01:34
Q75. In how many ways you can concatenate strings?
01:17
DOM - Introduction
00:30
Q76. What is DOM? What is the difference between HTML and
DOM?
02:31
Q77. How do you select, modify, create and remove DOM
elements?
00:56
Q78. What are selectors in JS?
01:05
Q79. Difference between
getElementById,getElementsByClassName& getElementsByTag?
02:42
Q80. What is the difference between querySelector() and
querySelectorAll()?
01:07
Q81. What are the methods to modify elements properties and
attributes?
00:39
Q82. What is the difference between innerHTML and textContent?
01:24
Q83. How to add and remove properties of HTML elements in the
DOM using JS?
01:07
Q84. How to add and remove style from HTML elements in DOM
using JS?
00:56
Q85. Create new elements in DOM using JS?
02:20
Q86. What is the difference between createElement() and
createTextNode()?
01:05
Error Handling- Introduction
00:27
Q87. What is Error Handling in JS?
01:16
Q88. What is the role of finally block in JS?
01:21
Q89. What is the purpose of the throw statement in JS?
400/411
01:30
Q90. What is Error propagation in JS?
00:38
Q91. What are the best practices for error handling?
01:02
Q92. What are the different types of errors In JS?
01:18
Objects - Introduction
00:33
Q93. What are Objects in JS?
02:00
Q94. In how many ways we can create an object?
01:36
Q95. What is the difference between an array and an object?
00:57
Q96. How do you add or modify or delete properties of an object?
00:37
Q97. Explain the difference between dot notation and bracket
notation?
01:24
Q98. What are some common methods to iterate over the
properties of an object?
01:32
Q99. How do you check if a property exists in an object?
01:23
Q100. How do you clone or copy an object?
01:48
Q101. What is the difference between deep copy and shallow copy
in JS?
02:46
Q102. What is Set Object in JS?
02:27
Q103. What is Map Object in JS?
01:26
Q104. What is the difference between Map and Object in JS?
01:01
Events - Introduction
00:32
Q105. What are Events? How are events triggered?
01:40
Q106. What are the types of events in JS?
01:05
Q107. What is Event Object in JS?
02:02
Q108. What is Event Delegation in JS?
02:01
401/411
Q109. What is Event Bubbling In JS?
01:40
Q110. How can you stop event propagation or event bubbling in
JS?
01:10
Q111. What is Event Capturing in JS?
01:42
Q112. What is the purpose of the event.preventDefault() method in
JS?
01:08
Q113. What is the use of "this" keyword in the context of event
handling in JS?
00:38
Q114. How to remove an event handler from an element in JS?
00:59
Closures - Introduction
00:30
Q115. Explain the concept of Lexical Scoping?
01:16
Q116. What is Closure?
01:53
Q117. What are the benefits of Closures?
04:34
Q118. What is the concept of Encapsulation in the context of
closures?
01:21
Q119. What are the disadvantage or limitations of Closures?
01:02
Q120. How can you release the variable references or closures
from memory?
00:26
Q121. What is the difference between a Regular Function and a
Closure?
00:59
Asynchronous programming – Basics - Introduction
00:35
Q122. What is asynchronous programming in JS? What is its use?
03:27
Q123. What is the difference between synchronous and
asynchronous programming?
01:39
Q124. What are the techniques for achieving asynchronous
operations in JS?
00:37
Q125. What is setTimeout()? How is it used to handle
asynchronous operations?
402/411
02:09
Q126. What is setInterval()? How is it used to handle asynchronous
operations?
01:33
Q127. What is the role of callbacks in fetching API data
asynchronously?
02:27
Q128. What is callback hell? How can it be avoided?
01:44
Asynchronous Programming - Promises - Introduction
00:35
Q129. What are Promises in JavaScript?
02:45
Q130. How to implement Promises in JavaScript?
02:30
Q131. When to use Promises in real applications?
00:47
Q132. What is the use of Promise.all() method?
02:11
Q133. What is the use of Promise.race() method?
01:23
Q134. What is the difference between Promise.all() and
Promise.race()?
01:08
Asynchronous Programming – Async Await - Introduction
00:22
Q135. What is the purpose of async/ await? Compare it with
Promises?
04:15
Q136. Explain the use of async and await keywords in JS?
03:04
Q137. Can we use async keyword without await keyword and vice
versa?
00:44
Q138. How do you handle errors in async/ await functions?
00:30
Browser APIs & Web Storage - Introduction
00:25
Q139. What is a window object?
01:01
Q140. What are Browser APIs in JS?
01:52
Q141. What is Web Storage, and its use? How many types of web
storage are there?
02:05
Q142. What is Local Storage? How to store, retrieve and remove
403/411
data from it?
02:21
Q143. What is Session Storage? How to store, retrieve and remove
data from it?
01:49
Q144. What is the difference between LocalStorage and
SessionStorage?
02:36
Q145. How much data can be stored in localStorage and
sessionStorage?
00:34
Q146. What are cookies? How do you create and read cookies?
01:49
Q147. What is the difference between cookies and web storage?
01:23
Q148. When to use cookies and when to use web storage?
01:22
Classes, Constructors, this & Inheritance - Introduction
00:15
Q149. What are Classes in JS?
03:08
Q150. What is a constructor?
00:50
Q151. What are constructor functions?
00:50
Q152. What is the use of this keyword?
01:33
Q153. Explain the concept of prototypal inheritance?
02:20
ECMAScript & Modules - Introduction
00:26
Q154. What is ES6? What are some new features introduced by it?
01:05
Q155. What are Modules in JS?
02:36
Q156. What is the role of export keyword?
00:51
Q157. What are the advantages of modules?
00:56
Q158. What is the difference between named exports and default
exports?
01:01
Q159. What is the difference between static and dynamic imports?
01:22
Q160. What are module bundlers?
01:23
404/411
Security & Performance - Introduction
00:23
Q161. What is eval() function in JS?
00:49
Q162. What is XSS (Cross-Site Scripting) attack?
01:01
Q163. What is SQL Injection attack?
00:52
Q164. What are some best practices for security in JS?
01:19
Q165. What are the best practices for improving performance in
JS?
Here’s a detailed explanation of key topics in JavaScript based on your provided list:
js
js
js
js
405/411
console.log(str.toUpperCase()); // "HELLO"
js
js
js
HTML is a static markup language that defines the structure of web pages, while DOM is a
dynamic, object-oriented representation of the HTML elements, allowing programs to access and
manipulate content.
406/411
querySelectorAll() : Selects all matching elements.
Number
String
Boolean
Object
Null
Undefined
Symbol (ES6)
1. Arithmetic Operators ( + , - , * , / , % )
2. Assignment Operators ( = , += , -= )
407/411
6. Ternary Operator ( condition ? expr1 : expr2 )
for loop
while loop
do...while loop
Named functions
Anonymous functions
408/411
js
Q14. What are Arrays in JS? How to Get, Add & Remove Elements?
Arrays store multiple values. Common operations:
Get: arr[index]
js
const person = {
name: "John",
age: 30
};
409/411
Hoisting is JavaScript’s behavior of moving declarations to the top of the scope during compile time.
Only the declaration is hoisted, not the initialization.
js
try {
// code that may throw an error
} catch (error) {
// handle the error
} finally {
// code that runs regardless of error
}
json
{
"name": "John",
"age": 30
}
410/411
These are the first 20 questions, but there are more detailed explanations available for all the topics
you've listed. Would you like to dive into more of them or focus on a specific one?
411/411