Angular Learning Resources Guide
Angular Learning Resources Guide
This repository contains a list of resources to learn Angular. It includes tutorials, articles,
videos, books, and other resources to help you learn Angular from scratch.
npm npm npm npm GitHub issues GitHub pull requests GitHub
GitHub last commit GitHub top language GitHub repo size
GitHub code size in bytes GitHub contributors GitHub forks GitHub stars
GitHub watchers
Table of Contents
Introduction
Features of Angular
Difference between AngularJS vs Angular
Angular vs React
Roadmap
Configuration
Prerequisites
Installation
Components
Three main building blocks
Component Creation
Using Angular CLI
Manual Creation
Example
Scope
View Encapsulation
Emulated View Encapsulation
Shadow DOM View Encapsulation
None View Encapsulation
Component Communication
Parent to Child
Child to Parent
Standalone Components
Data Binding
One Way Binding
Two Way Binding
Directives
Structural Directives
Attribute Directives
Custom Directives
Other Directives
New Control Flow
Pipes
Date Pipe
Uppercase Pipe
Lowercase Pipe
Currency Pipe
Percent Pipe
Slice Pipe
Decimal/number Pipe
JSON Pipe
Async Pipe
Decorators
Input
Output
HostListener
ContentChild & ContentChildren
ViewChild & ViewChildren
HostListener
ContentChild & ContentChildren
ViewChild & ViewChildren
Life Cycle Hooks
OnChanges
OnInit
DoCheck
AfterViewInit
AfterViewChecked
AfterContentInit
AfterContentChecked
OnDestroy
Forms
Template Driven Forms
Reactive Forms
Services
Injectable Decorator
Dependency Injection
Providers
Routing
Router Outlet
Router Link
Router Link Active
Router State
Router Events
Router Guards
Lazy Loading
HTTP Client
Destroy Ref
Http
Module
Router
Route Parameter
Route Guards
Observables
Creating Observables
Subscribing to Observables
Difference between Observables and Promises in Angular
Unsubscribe
Renderer2
JIT
AOT
Deferrable Views
Meta Tags
Title Service
Dynamic Title
Meta Service
Angular Signals
Security
Preventing cross-site scripting (XSS)
Angular’s cross-site scripting security model
Preventing cross-site scripting (XSS)
Angular’s cross-site scripting security model
Sanitization and security contexts
Sanitization example
Direct use of the DOM APIs and explicit sanitization calls
Trusting safe values
Content security policy
Enforcing Trusted Types
Use the AOT template compiler
Server-side XSS protection
HTTP-level vulnerabilities
Cross-site request forgery
HttpClient XSRF/CSRF security
Configure custom cookie/header names
Disabling XSRF protection
Cross-site script inclusion (XSSI)
Auditing Angular applications
Angular Animations
Installing Angular Animations
Angular Universal
Creating an Angular Universal application
Bootstrap
Installing Bootstrap
Importing Bootstrap
Angular Material
Installing Angular Material
Importing Angular Material
Tailwind CSS
Installing Tailwind CSS
Importing Tailwind CSS
PrimeNG
Installing PrimeNG
Importing PrimeNG
SPA
Advantages of SPA
PWA
Installing PWA
Configuring PWA
Building PWA
Service Worker
Features of PWA
CLI Commands
Version compatibility
Deploying an Angular Application
Imports
TypeScript
RxJS
Learn From GitHub Repositories
Learn From Websites
Learn From Books
Learn From YouTube Channels
Learn More From Blogs Sites
List of Online Editors/Compiler for Angular
List of Twitter Users to Follow
List of LinkedIn Users to Follow
List of Discord Servers to Join
Introduction
Angular is a popular open-source framework by Google for building single-page and
dynamic web applications. It offers tools and libraries for components, services, forms,
routing, and HTTP client, all built with TypeScript. Angular is known for its
performance, scalability, and developer productivity.
Features of Angular
Component-Based Architecture: Reusable, self-contained units of code that define
the UI and behavior of a part of the application.
Two-Way Data Binding: Automatic synchronization of data between the model and
the view.
Dependency Injection: Provides components with the services they need for better
modularity and testability.
Routing: Powerful system for navigation between different views, supporting deep
linking, lazy loading, and route guards.
Forms: Tools for template-driven and reactive forms, based on a model-driven
approach.
HTTP Client: Simple API for making HTTP requests and handling responses.
Observables: Handles asynchronous operations and event handling.
TypeScript: Superset of JavaScript with static typing, better tooling, error checking,
and code completion.
Performance: Optimized for performance with virtual DOM, lazy loading, tree
shaking, and ahead-of-time compilation.
Mobile Support: Tools for building responsive, touch-friendly mobile applications,
including PWAs.
SEO Friendly: Tools for server-side rendering, pre-rendering, and meta tags to
improve search engine visibility.
Community Support: Large, active community providing support and sharing
knowledge.
AngularJS Angular
Based on MVC Architecture Based on Components
AngularJS Angular
Uses JavaScript to build the
Uses TypeScript to build the application
application
No Mobile Support Mobile supports
Runs on both client-side as well as server-
Run on only client-side
side
CLI not present CLI present
No SEO Friendly Seo Friendly
Performance is slow Performance is fast
Back to top⤴️
Angular vs React
Angular: A full-fledged framework by Google for building web applications. It
includes features like two-way data binding, routing, forms, and HTTP client. Ideal
for large, complex applications needing a complete solution.
Comparison: Angular offers a complete solution with built-in features, while React
focuses on the view layer, allowing developers to choose additional tools and libraries.
When to use Angular: Best for large, complex applications needing integrated tools and
scalability.
When to use React: Best for small to medium-sized applications needing flexibility and
a focus on the UI.
Back to top⤴️
Roadmap
Angular Roadmap
Configuration
Prerequisites
[Link]
NPM
Angular CLI
Installation
If you are using pnpm, you can use the following command:
If you are using yarn, you can use the following command:
If you are using bun, you can use the following command:
If you want to install a specific version of the Angular CLI, you can use the following
command:
If you have already installed the Angular CLI, you can update it to the latest version
using the following command:
Check version
ng version
Create a new Angular project: (Replace [PROJECT NAME] with your project name)
## without routing
ng new [PROJECT NAME] --routing=false
## without testing
ng new [PROJECT NAME] --skip-tests=true
## without dependencies
ng new [PROJECT NAME] --skip-install=true
## without git
ng new [PROJECT NAME] --skip-git=true
cd [PROJECT NAME]
ng serve
[PROJECT NAME]
├── node_modules
├── src
│ ├── app
│ │ ├── [Link]
│ │ ├── [Link]
│ │ ├── [Link]
│ │ ├── [Link]
│ │ ├── [Link]
│ │ ├── ...
│ ├── assets
│ │ ├── .gitkeep
│ │ └── ...
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ └── ...
├── .editorconfig
├── .gitignore
├── [Link]
├── [Link]
├── [Link]
├── [Link]
├── [Link]
└── ...
[PROJECT NAME]
├── node_modules
├── public
│ ├── [Link]
│ └── ...
├── src
│ ├── app
│ │ ├── [Link]
│ │ ├── [Link]
│ │ ├── [Link]
│ │ ├── [Link]
│ │ ├── [Link]
│ │ ├── [Link]
│ │ └── ...
│ ├── [Link]
│ ├── [Link]
│ ├── [Link]
│ └── ...
├── .editorconfig
├── .gitignore
├── [Link]
├── [Link]
├── [Link]
├── [Link]
├── [Link]
└── ...
Back to top ⤴️
Components
Component is the main building block of an Angular Application. It is a TypeScript class
that interacts with the HTML template and provides the data and logic to the view.
Template
Class
Metadata
There are several properties that can be defined in the component metadata:
Selector
Providers
Styles
StyleUrls
Template
TemplateUrl
Selector - Defines the element name or CSS selector that identifies the component in the
HTML template.
selector: 'app-root'
providers: [MyService]
styleUrls: ['./[Link]']
templateUrl - Defines the URL of the HTML template for the component.
templateUrl: './[Link]'
Component Creation
# or
ng g c [component-name]
Manual Creation
Step 1 - Create a new folder for the component inside the src/app folder.
src/app/[component-name]
Step 2 - Create a new TypeScript file for the component inside the new folder.
src/app/[component-name]/[component-name].[Link]
Step 3 - Create a new HTML file for the component inside the new folder.
src/app/[component-name]/[component-name].[Link]
Step 4 - Create a new CSS file for the component inside the new folder.
src/app/[component-name]/[component-name].[Link]
@Component({
selector: 'app-[component-name]',
standalone: true,
templateUrl: './[component-name].[Link]',
styleUrls: ['./[component-name].[Link]']
})
If you want to create a non-standalone component, set the standalone property to false.
The standalone component is enabled by default in Angular v17 and v18. In Angular v19
and later, the standalone component is enabled by default and the standalone property is
not required. You can disable the standalone component by setting the standalone
property to false.
Step 7 - Define the selector, template, and styles for the component.
Step 10 - Add the component to the declarations array in the @NgModule decorator.
declarations: [
AppComponent,
[ComponentName]Component
]
If you created a standalone component, [Link] file is not required. You can
import the component in the [Link] file. as shown below.
import { [ComponentName]Component } from './[component-name]/[component-
name].component';
@Component({
selector: 'app-root',
standalone: true,
imports: [[ComponentName]Component],
templateUrl: './[Link]',
styleUrl: './[Link]'
})
<app-[component-name]></app-[component-name]>
ng serve
# or
ng serve --open
Example
//[Link]
import { Component } from '@angular/core';
@Component({
selector: 'test-component',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
<!--[Link]-->
<h1>Test Component</h1>
/*[Link]*/
h1 {
color: red;
}
//[Link]
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
//[Link]
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { TestComponent } from './[Link]';
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrl: './[Link]'
})
export class AppComponent {
title = 'app';
}
<!--[Link]-->
<app-test-component></app-test-component>
//[Link]
import { Component } from '@angular/core';
@Component({
selector: 'app-test-component',
standalone: true,
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
/*[Link]*/
h1 {
color: red;
}
//[Link]
import { Component } from '@angular/core';
import { TestComponent } from './[Link]';
@Component({
selector: 'app-root',
imports: [TestComponent],
templateUrl: './[Link]',
styleUrl: './[Link]'
})
export class AppComponent {
title = 'app';
}
In version 17 and 18 of Angular, the standalone component is enabled by default with the
standalone property set to true in the @Component decorator. You can disable the
standalone component by setting the standalone property to false or not adding the
standalone property in the @Component decorator.
//[Link]
import { Component } from '@angular/core';
@Component({
selector: 'app-test-component',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
<!--[Link]-->
<h1>Test Component</h1>
/*[Link]*/
h1 {
color: red;
}
@Component({
selector: 'app-root',
imports: [TestComponent],
templateUrl: './[Link]',
styleUrl: './[Link]'
})
export class AppComponent {
title = 'app';
}
<!--[Link]-->
<app-test-component></app-test-component>
In version 19 and later of Angular, the standalone component is enabled by default. You
can disable the standalone component by setting the standalone property to false in the
@Component decorator.
Inside app folder, [Link] file is created by default in version 17 and later of
Angular. And [Link] file is created by default in version 17 and later of Angular.
// [Link]
import { ApplicationConfig, provideZoneChangeDetection } from
'@angular/core';
import { provideRouter } from '@angular/router';
// [Link]
import { Routes } from '@angular/router';
You can import the component in the [Link] file and use the component
selector in the HTML template.
@Component({
selector: 'app-root',
template: '<h1> {{title}} works </h1>',
styles: ['h1 { font-weight: bold; }']
})
export class AppComponent {
title = 'app';
}
Back to top ⤴️
Scope
In Angular, the scope of a variable determines where it can be accessed:
Global Scope
Accessible from anywhere in the application; defined outside any function or block.
Example :
// Global Scope
let globalVariable = 'Global Variable';
function testFunction() {
[Link](globalVariable); // Output: Global Variable
}
testFunction();
Example in Angular :
// Global Scope
let globalVariable = 'Global Variable';
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
<!--[Link]-->
<h1>{{ title }}</h1>
Local Scope
Example :
function testFunction() {
// Local Scope
let localVariable = 'Local Variable';
[Link](localVariable); // Output: Local Variable
}
testFunction();
[Link](localVariable); // Error: localVariable is not defined
Example in Angular :
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
<!--[Link]-->
<button (click)="testFunction()">Test Function</button>
Component Scope
Accessible within the component and its children.
Example :
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
<!--[Link]-->
<h1>{{ title }}</h1>
Back to top⤴️
View Encapsulation
Controls how styles are applied to components. By default, Angular uses Emulated View
Encapsulation, scoping styles to the component.
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
encapsulation: [Link]
})
export class AppComponent {
title = 'app';
}
Stackblitz Example
Uses native shadow DOM to encapsulate styles within the component, preventing them
from affecting other components.
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
encapsulation: [Link]
})
export class AppComponent {
title = 'app';
}
Stackblitz Example
None View Encapsulation
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
encapsulation: [Link]
})
export class AppComponent {
title = 'app';
}
Stackblitz Example
Back to top ⤴️
Component Communication
Passing data between Angular components using Input/Output decorators, EventEmitter,
and services.
Parent to Child
Input Decorator - The @Input decorator is used to pass data from a parent component to
a child component. It allows the parent component to bind a property to the child
component.
Example :
@Component({
selector: 'app-child',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
<!--[Link]-->
<p>{{ message }}</p>
@Component({
selector: 'app-parent',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
<!--[Link]-->
<app-child [message]="message"></app-child>
Stackblitz Example
Child to Parent
Output Decorator - The @Output decorator is used to pass data from a child component
to a parent component. It allows the child component to emit events that the parent
component can listen to.
Example :
@Component({
selector: 'app-child',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
sendMessage() {
[Link]('Hello from child component');
}
}
<!--[Link]-->
<button (click)="sendMessage()">Send Message</button>
@Component({
selector: 'app-parent',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
<!--[Link]-->
<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>{{ message }}</p>
Stackblitz Example
Back to top⤴️
Siblings to Siblings Communication
Using Services - Services are a way to share data and functionality between components
in Angular. You can create a service that holds the data and methods that need to be
shared between components.
Example 1 :
@Injectable({
providedIn: 'root'
})
setMessage(message: string) {
[Link] = message;
}
getMessage() {
return [Link];
}
}
@Component({
selector: 'app-sibling1',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
<!--[Link]-->
<button (click)="sendMessage()">Send Message</button>
@Component({
selector: 'app-sibling2',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
receiveMessage() {
[Link] = [Link]();
}
}
<!--[Link]-->
<p>{{ message }}</p>
<button (click)="receiveMessage()">Receive Message</button>
Stackblitz Example
Example 2 :
Using RxJS Subjects - RxJS Subjects are a way to share data and events between
components in Angular. You can create a Subject that emits events and subscribe to those
events in the components.
@Injectable({
providedIn: 'root'
})
setMessage(message: string) {
[Link](message);
}
}
@Component({
selector: 'app-sibling1',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
sendMessage() {
[Link]('Hello from sibling1 component');
}
}
<!--[Link]-->
<button (click)="sendMessage()">Send Message</button>
@Component({
selector: 'app-sibling2',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
ngOnInit() {
[Link](message => {
[Link] = message;
});
}
}
<!--[Link]-->
<p>{{ message }}</p>
Example 3 :
Using ViewChild and ViewChildren - ViewChild and ViewChildren are a way to access
child components in Angular. You can use ViewChild to access a single child component
and ViewChildren to access multiple child components.
@Component({
selector: 'app-sibling1',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
sendMessage() {
[Link] = 'Hello from sibling1 component';
}
}
<!--[Link]-->
<button (click)="sendMessage()">Send Message</button>
<app-sibling2></app-sibling2>
@Component({
selector: 'app-sibling2',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
<!--[Link]-->
<p>{{ message }}</p>
Stackblitz Example
Back to top⤴️
Standalone Components
A standalone component is a type of component which is not part of any Angular module.
It provides a simplified way to build Angular applications by reducing the need for
NgModules. Standalone components are self-contained and declare their own
dependencies.
Creating a Standalone Component
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-standalone',
standalone: true, // Mark as standalone
imports: [CommonModule], // Import required dependencies
template: `
<h1>Standalone Component</h1>
<p>This is a self-contained component</p>
`
})
export class StandaloneComponent {
// Component logic here
}
bootstrapApplication(AppComponent, {
providers: [
// Root providers here
]
});
Converting to Standalone
Back to top ⤴️
Data binding
Data binding is a core feature of Angular that allows you to bind data between the
component’s class and the HTML template. There are two types of data binding in
Angular:
One-way binding - This allows for passing data from the component’s class to the
HTML template or vice-versa.
One-way binding allows for passing data from the component’s class to the HTML
template.
1. From Component to View - This allows for passing data from the component’s class
to the HTML template.
There are several ways to achieve one-way binding from the component to the view in
Angular, including:
1. Interpolation
2. Property binding
3. Class binding
4. Style binding
5. Attribute binding
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
firstText = 'Interpolation';
lastText = 'Example';
}
Stackblitz Example
Property binding - This allows for binding a property of an HTML element to a property
in the component’s class. It is denoted by square brackets ([]).
Example :
<h1 [innerText]="title"></h1>
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
title = 'Angular Property Binding Example';
isDisabled = true;
}
Stackblitz Example
class binding - This allows for binding a class of an HTML element to a property in the
component’s class. It is denoted by square brackets ([]).
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
isActive = false;
toggleActive() {
[Link] = ![Link];
}
}
.active {
background-color: yellow;
}
Stackblitz Example
style binding - This allows for binding a style of an HTML element to a property in the
component’s class. It is denoted by square brackets ([]).
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
backgroundColor = 'red';
textColor = 'white';
}
<div [[Link]-color]="backgroundColor">
<h1 [[Link]]="textColor">Hello, world!</h1>
</div>
Stackblitz Example
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
imageUrl = '[Link]
imageAlt = 'Example image';
isButtonDisabled = false;
}
Stackblitz Example
b. From View to Component - This allows for passing data from the HTML template to
the component’s class.
There are several ways to achieve one-way binding from the view to the component in
Angular, including:
1. Event binding
2. ngModel
Event binding - This allows for binding an event of an HTML element to a method in
the component’s class. It is denoted by parentheses (()).
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: [ './[Link]' ]
})
export class AppComponent {
onClick() {
[Link]('Button was clicked');
}
}
Stackblitz Example
ngModel - The ngModel directive is used to create two-way data binding between an
input element and a property in the component’s class. It is commonly used to bind form
controls to properties in the component.
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
name: string = '';
}
Remeber 💡:
The (click) calls the specified function when a user clicks on the given element (in your
example, when a user clicks on a row).
The (change) event binds to HTML’s onChange event. This event is fired for <input>,
<select>, and <textarea> elements when a change to the element’s value is committed
by the user.
The (change) event can also be specifically implemented by other Angular components. It
is generally implemented on components where the contents of the component are
changed by the user.
☝️Source of Explaination
Two ways binding
Two-way binding allows for binding a property of an HTML element to a property in the
component’s class and vice-versa. It is denoted by [(ngModel)].
1. ngModel
2. ngModelChange
3. change event
ngModel - The ngModel directive is used to create two-way data binding between an
input element and a property in the component’s class. It is commonly used to bind form
controls to properties in the component.
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
name: string = '';
}
Stackblitz Example
Back to top⤴️
ngModelChange - The ngModelChange event is emitted when the value of an input
element bound to ngModel changes. It can be used to perform additional logic when the
value changes.
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
onNameChange(value: string) {
[Link]('Name changed to:', value);
}
}
Stackblitz Example
change event - The change event is emitted when the value of an input element changes.
It can be used to perform additional logic when the value changes.
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
onNameChange(value: string) {
[Link]('Name changed to:', value);
}
}
Stackblitz Example
Back to top ⤴️
Directives
Directives add behaviour to an existing DOM element or an existing component instance.
Types of Directives
There are three types of directives in Angular:
3. Custom Directives - Custom directives are user-defined directives that add custom
behavior to an element. They can be used to encapsulate complex behavior and reuse
it across multiple components.
Structural Directives
There are several built-in structural directives in Angular, including:
1. NgIf
2. NgFor
3. NgSwitch
ngIf - The ngIf directive is used to conditionally display elements based on the value of a
given expression. It is commonly used to show or hide elements in the UI based on
certain conditions.
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
showElement = true;
}
<h1>ngIf Example</h1>
<div *ngIf="showElement">
This element will only be displayed if showElement is true.
</div>
Stackblitz Example
ngFor - The ngFor directive is used to iterate over a list of items and create a template for
each item. It is commonly used to display a list of items in the UI.
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
<h1>ngFor Example</h1>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
Stackblitz Example
ngSwitch - The ngSwitch directive is used to conditionally display elements based on the
value of a given expression. It is similar to a switch statement in JavaScript.
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
value = 1;
}
<h1>ngSwitch Example</h1>
<div [ngSwitch]="value">
<div *ngSwitchCase="1">Case 1</div>
<div *ngSwitchCase="2">Case 2</div>
<div *ngSwitchCase="3">Case 3</div>
<div *ngSwitchDefault>Default case</div>
</div>
Stackblitz Example
Attribute Directives
1. NgClass
2. NgStyle
3. NgModel
ngClass - The ngClass directive is used to conditionally apply CSS classes to an element
based on the value of a given expression. It is commonly used to apply styles to elements
based on certain conditions.
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
isHighlighted = true;
}
<h1>ngClass Example</h1>
<div [ngClass]="{ highlighted: isHighlighted }">
This element will have the 'highlighted' class if isHighlighted is true.
</div>
.highlighted {
background-color: yellow;
}
Stackblitz Example
ngStyle - The ngStyle directive is used to conditionally apply inline styles to an element
based on the value of a given expression. It is commonly used to apply dynamic styles to
elements based on certain conditions.
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
color = 'red';
}
<h1>ngStyle Example</h1>
<div [ngStyle]="{ color: color }">
This element will have the color style set to the value of the color
property.
</div>
Stackblitz Example
ngModel - The ngModel directive is used to create two-way data binding between an
input element and a property in the component’s class. It is commonly used to bind form
controls to properties in the component.
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
name: string;
}
<h1>ngModel Example</h1>
<form>
<label for="name">Name:</label>
<input type="text" id="name" [(ngModel)]="name" name="name" />
</form>
Stackblitz Example
Custom Directives
Custom directives are user-defined directives that add custom behavior to an element.
They can be used to encapsulate complex behavior and reuse it across multiple
components.
Example :
@Directive({
selector: '[appCustomDirective]',
})
export class CustomDirectiveDirective {
constructor(private el: ElementRef) {}
@HostListener('mouseenter') onMouseEnter() {
[Link]('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
[Link](null);
}
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, CustomDirectiveDirective],
bootstrap: [AppComponent],
})
export class AppModule {}
Stackblitz Example
Back to top ⤴️
Other directives
ngContainer
ngTemplate
ngContent
ngTemplateOutlet
ngContainer - The ngContainer directive is a simple container that doesn’t generate any
markup in the DOM. It’s mainly used as a placeholder to group and structure content
within Angular templates.
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
<h1>ngContainer Example</h1>
<div *ngIf="condition">
<ng-container>
<p>Content to be conditionally rendered</p>
<p>More content...</p>
</ng-container>
</div>
Stackblitz Example
ngTemplate - The ngTemplate directive is used to define a reusable template block that
can be used later within the same component or shared across components using the
ngTemplateOutlet directive.
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
<h1>ngTemplate Example</h1>
<ng-template #myTemplate>
<p>This is a template</p>
<p>It can be reused in multiple places</p>
</ng-template>
<div>
<ng-container *ngTemplateOutlet="selectedTemplate"></ng-container>
</div>
Stackblitz Example
Example :
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
@Component({
selector: 'app-parent',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
Stackblitz Example
Example :
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
<h1>ngTemplateOutlet Example</h1>
<ng-container *ngTemplateOutlet="selectedTemplate"></ng-container>
<ng-template #template1>
Template 1 content
</ng-template>
<ng-template #template2>
Template 2 content
</ng-template>
Stackblitz Example
@if (a > b) {
<p>{{a}} is greater than {{b}}</p>
}
@if (a > b) {
{{a}} is greater than {{b}}
} @else if (b > a) {
{{a}} is less than {{b}}
} @else {
{{a}} is equal to {{b}}
}
@switch (userPermissions) {
@case ('admin') {
<app-admin-dashboard />
}
@case ('reviewer') {
<app-reviewer-dashboard />
}
@case ('editor') {
<app-editor-dashboard />
}
@default {
<app-viewer-dashboard />
}
}
Back to top⤴️
Pipes
A pipe takes in data as input and transforms it to a desired output.
Syntax:
{{ data | pipe }}
Expression | pipeOperator[:pipeArguments]
Built-in Pipes
There are several built-in pipes in Angular, including:
Date Pipe
Uppercase Pipe
Lowercase Pipe
Currency Pipe
Percent Pipe
Slice Pipe
Decimal/number Pipe
JSON Pipe
Async Pipe
Date Pipe
The date pipe is used to format a date value according to the locale rules specified in the
application.
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
date = new Date();
formatDate() {
return [Link]([Link], 'shortDate');
}
}
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [DatePipe],
})
export class AppModule {}
Stackblitz Example
Uppercase Pipe
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
name = 'Manthan Ank';
}
Stackblitz Example
Lowercase Pipe
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
name = 'Manthan Ank';
}
Stackblitz Example
Currency Pipe
The currency pipe is used to format a number as currency using the locale rules specified
in the application.
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
price = 100;
formatCurrency() {
return [Link]([Link], 'USD', true);
}
}
Stackblitz Example
Percent Pipe
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
percentage = 0.5;
formatPercentage() {
return [Link]([Link], '2');
}
}
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [PercentPipe],
})
export class AppModule {}
Stackblitz Example
Slice Pipe
The slice pipe is used to create a new array or string containing a subset of the elements
of the input array or string.
Stackblitz Example
Decimal/number Pipe
The number pipe is used to format a number as text. It can be used to format a number as
a percentage, currency, or decimal number.
Stackblitz Example
JSON Pipe
The json pipe is used to transform a JavaScript object into a JSON string.
<p>{{data | json}}</p>
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
Stackblitz Example
Async Pipe
The async pipe is used to subscribe to an Observable or Promise and return the latest
value it has emitted.
<p>{{data$ | async}}</p>
// [Link]
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable()
export class DataService {
private data$: Observable<string>;
constructor() {
// Simulating an asynchronous data source
[Link]$ = of('Hello, async pipe!').pipe(
// Simulating delay
delay(2000)
);
}
getData(): Observable<string> {
return [Link]$;
}
}
// [Link]
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { DataService } from './[Link]';
@Component({
selector: 'app-example',
template: '<div>{{ data$ | async }}</div>',
})
export class ExampleComponent {
data$: Observable<string>;
Stackblitz Example
Impure Pipes
By default, Angular pipes are pure, meaning they are stateless and do not change unless
the input value changes. However, you can create impure pipes by setting the pure
property to false in the @Pipe decorator.
@Pipe({
name: 'impurePipe',
pure: false,
})
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, ImpurePipe],
bootstrap: [AppComponent],
})
export class AppModule {}
Stackblitz Example
Back to top⤴️
Decorators
Decorators are design patterns used to isolate the modification or decoration of a class
without modifying the source code.
@Component
@Directive
@Injectable
@Pipe
@NgModule
@Input
@Output
@HostListener
@ContentChild
@ContentChildren
@ViewChild
@ViewChildren
Component
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
Directive
The @Directive decorator is used to define a new directive in Angular.
@Directive({
selector: '[appCustomDirective]',
})
@HostListener('mouseenter') onMouseEnter() {
[Link]('yellow');
}
@HostListener('mouseleave') onMouseLeave() {
[Link](null);
}
private highlight(color: string) {
[Link] = color;
}
}
<div appCustomDirective>
This element will have a yellow background when the mouse is over it.
</div>
@NgModule({
declarations: [CustomDirective],
})
Injectable
@Injectable
export class DataService {
getData() {
return 'Hello, world!';
}
}
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
@NgModule({
declarations: [AppComponent],
providers: [DataService],
})
Pipe
@Pipe({
name: 'customPipe',
})
@NgModule({
declarations: [CustomPipe],
})
NgModule
@NgModule({
imports: [],
declarations: [],
providers: [],
bootstrap: [],
})
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
Input
The @Input decorator is used to pass data from a parent component to a child component.
@Component({
selector: 'app-child',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class ChildComponent implements OnInit {
@Input() message: string;
constructor() { }
ngOnInit() {}
@Component({
selector: 'app-parent',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class ParentComponent implements OnInit {
parentMessage = 'Hello from the parent component!';
constructor() {}
ngOnInit() {}
}
<app-child [message]="parentMessage"></app-child>
<h1>@Input Example</h1>
<app-parent></app-parent>
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [BrowserModule, FormsModule, RouterModule],
declarations: [AppComponent, ChildComponent, ParentComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
Output
The @Output decorator is used to pass data from a child component to a parent
component.
@Component({
selector: 'app-child',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class ChildComponent implements OnInit {
@Output() messageEvent = new EventEmitter<string>();
constructor() {}
ngOnInit() {}
sendMessage() {
[Link]('Hello from the child component!');
}
}
@Component({
selector: 'app-parent',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class ParentComponent implements OnInit {
constructor() {}
ngOnInit() {}
handleMessage(message: string) {
[Link](message);
}
}
<app-child (messageEvent)="handleMessage($event)"></app-child>
HostListener
The @HostListener decorator is used to listen for events on the host element of a
directive or component.
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
@HostListener('click')
onClick() {
[Link]('The host element was clicked!');
}
}
The @ContentChild and @ContentChildren decorators are used to query for content
children in the component’s view.
import {
Component,
ContentChild,
ContentChildren,
ElementRef,
OnInit,
QueryList,
} from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class ParentComponent implements OnInit {
@ContentChild('childButton1', { static: true }) childButton1: ElementRef;
@ContentChildren('childButton2') childButtons2: QueryList<ElementRef>;
ngAfterContentInit() {
[Link]([Link]);
[Link]((button) => {
[Link]([Link]);
});
}
constructor() {}
ngOnInit() {}
}
<ng-content></ng-content>
The @ViewChild and @ViewChildren decorators are used to query for view children in the
component’s view.
import { Component, ElementRef, QueryList, ViewChild, ViewChildren } from
'@angular/core';
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: [ './[Link]' ]
})
export class AppComponent {
@ViewChild('childButton1', { static: true }) childButton1: ElementRef;
@ViewChildren('childButton2') childButtons2: QueryList<ElementRef>;
ngAfterViewInit() {
[Link]([Link]);
[Link](button => {
[Link]([Link]);
});
}
}
ngOnChanges
ngOnInit
ngDoCheck
ngAfterContentInit
ngAfterContentChecked
ngAfterViewInit
ngAfterViewChecked
ngOnDestroy
OnChanges
It is called when the data-bound properties of a directive/component are changed. It is
called before ngOnInit and whenever one or more data-bound input properties change.
<form>
<input [(ngModel)]="message" name="message" />
<button type="submit" (click)="onSubmit()">Submit</button>
</form>
<p>{{ message }}</p>
import {
Component,
Input,
OnChanges,
OnInit,
SimpleChanges,
} from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class TestComponent implements OnChanges {
@Input() message: string;
prevMessage: string;
ngOnChanges(changes: SimpleChanges) {
if ([Link]) {
[Link](
`message changed from ${[Link]} to
${[Link]}`
);
}
}
onSubmit() {
[Link] = [Link];
}
}
Stackblitz Link
OnInit
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
constructor() {}
ngOnInit() {
[Link]('logged from ngOnInit');
}
}
Stackblits Link
DoCheck
It is called during every change detection run, and it is used to detect and act upon
changes that Angular doesn’t catch on its own.
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent implements DoCheck {
ngDoCheck() {
[Link]('ngDoCheck Called');
}
}
Stackblitz Link
AfterViewInit
It is called after Angular has fully initialized a component’s view. It is the perfect place to
put any initialization logic that depends on the view.
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent implements AfterViewInit{
ngAfterViewInit(){
[Link]("after view init")
}
clickMe(){
[Link]("link clicked")
}
}
Stackblitz Link
AfterViewChecked
It is called after Angular has checked the component’s view and child views. It is called
after ngAfterViewInit and every subsequent ngAfterContentChecked.
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent implements AfterViewChecked {
ngAfterViewChecked(){
[Link]("after view checked")
}
clickMe(){
[Link]("link clicked")
}
}
<a (click)="clickMe()">Click me</a>
Stackblitz Link
AfterContentInit
It is called after Angular has fully initialized the content of a directive. It is the perfect
place to put any initialization logic that depends on the content.
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent implements AfterContentInit {
ngAfterContentInit() {
[Link]('after content init');
}
clickMe() {
[Link]('clicked');
}
}
Stackblitz Link
AfterContentChecked
It is called after the default change detector has completed checking all content of a
directive. It is called after ngAfterContentInit and every subsequent
ngAfterContentChecked.
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent implements AfterContentInit {
ngAfterContentChecked() {
[Link]('after content init');
}
clickMe() {
[Link]('clicked');
}
}
OnDestroy
It is called just before Angular destroys the directive/component. It is used to cleanup any
resources or subscriptions that the directive/component has created.
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent implements OnInit, OnDestroy {
private subscription: Subscription;
ngOnInit() {
const someObservable = of(1, 2, 3);
[Link] = [Link]((data) => {
[Link](data);
});
}
ngOnDestroy() {
[Link]();
}
}
Stackblitz Link
Back to top⤴️
Forms
Angular provides two types of forms:
Template-driven forms
Reactive forms
Template-driven Forms
Template-driven forms are created using directives in the template. Angular automatically
tracks the value and validity of the form controls.
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
export class AppComponent {
onSubmit(form: NgForm) {
[Link]([Link]);
}
}
Reactive Forms
Reactive forms are created programmatically using form controls and form groups. They
provide more control and flexibility compared to template-driven forms.
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
onSubmit() {
[Link]([Link]);
}
}
Back to top⤴️
Set Value in Template Driven forms in Angular
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
Back to top⤴️
FormBuilder in Reactive Forms
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
onSubmit() {
[Link]([Link]);
}
}
[Link]({
name: 'John',
email: '[Link]@[Link]',
});
[Link]({
name: 'Jane',
});
}
onSubmit() {
[Link]([Link]);
}
}
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
[Link]((status) => {
[Link](status);
});
}
onSubmit() {
[Link]([Link]);
}
}
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
[Link]((value) => {
[Link](value);
});
}
onSubmit() {
[Link]([Link]);
}
}
FormControl
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
FormGroup
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
onSubmit() {
[Link]([Link]);
}
}
FormArray Example
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
addEmail() {
[Link]([Link](''));
}
removeEmail(index: number) {
[Link](index);
}
onSubmit() {
[Link]([Link]);
}
}
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
get addresses() {
return [Link]('addresses') as FormArray;
}
addAddress() {
[Link](
[Link]({
street: '',
city: '',
state: '',
zip: '',
})
);
}
removeAddress(index: number) {
[Link](index);
}
onSubmit() {
[Link]([Link]);
}
}
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
[Link]({
name: 'John',
addresses: [
{ street: '123 Main St', city: 'Anytown', state: 'CA', zip: '12345'
},
{ street: '456 Elm St', city: 'Othertown', state: 'NY', zip: '67890'
},
],
});
[Link]({
name: 'Jane',
});
}
get addresses() {
return [Link]('addresses') as FormArray;
}
addAddress() {
[Link](
[Link]({
street: '',
city: '',
state: '',
zip: '',
})
);
}
removeAddress(index: number) {
[Link](index);
}
onSubmit() {
[Link]([Link]);
}
}
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
onSubmit() {
[Link]([Link]);
}
}
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
onSubmit() {
[Link]([Link]);
}
}
FormArray in Angular
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
Services
Services are used to encapsulate reusable functionality that can be shared across
components. They are used to fetch data from a server, perform calculations, or interact
with external services.
@Injectable
export class DataService {
getData() {
return 'Data from the service';
}
}
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
Back to top⤴️
Injectable Decorator
The @Injectable decorator is used to define a service class that can be injected into other
components or services.
import { Injectable } from '@angular/core';
@Injectable
export class DataService {
getData() {
return 'Data from the service';
}
}
Back to top⤴️
Dependency Injection
Dependency injection is a design pattern used to create objects and manage their
dependencies. It allows you to inject dependencies into a class rather than creating them
within the class.
@Injectable
export class DataService {
getData() {
return 'Data from the service';
}
}
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
@Component({
selector: 'my-app',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
})
constructor() {
[Link] = [Link]();
}
}
Back to top ⤴️
Providers
Providers are used to define dependencies that are injected into components, directives,
pipes, and services. They are defined in the @NgModule decorator of the root module or
feature modules.
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
providers: [DataService],
})
Back to top ⤴️
Routing
Routing is used to navigate between different components in an Angular application. It
allows users to move between different parts of the application by changing the URL in
the browser.
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule],
})
Back to top⤴️
Router Outlet
The router-outlet directive is used to render the component associated with the current
route.
<router-outlet></router-outlet>
Back to top⤴️
Router Link
The routerLink directive is used to navigate to a different route when the element is
clicked.
<a [routerLink]="['/home']">Home</a>
Back to top⤴️
Router Link Active
The routerLinkActive directive is used to add a CSS class to an element when the
associated route is active.
Back to top⤴️
Router Link Active Options
Back to top⤴️
Router State
The RouterState class is used to access the current state of the router.
Back to top⤴️
Router Events
The RouterEvents class is used to listen for router events such as navigation start,
navigation end, and navigation error.
import { Router, NavigationStart, NavigationEnd, NavigationError } from
'@angular/router';
Back to top⤴️
Router Guards
Router guards are used to control navigation and access to routes in an Angular
application. They can be used to prevent unauthorized access to certain routes, redirect
users to a login page, or perform other actions before navigating to a route.
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate() {
if ([Link]('token')) {
return true;
} else {
[Link](['/login']);
return false;
}
}
}
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule],
providers: [AuthGuard],
})
Back to top⤴️
HTTP Client Module
The HttpClientModule is used to make HTTP requests to a server in an Angular
application. It provides services for making GET, POST, PUT, DELETE, and other types
of requests.
@NgModule({
imports: [HttpClientModule],
})
export class AppModule {}
In the angular v17 and above, the HttpClientModule has been deprecated. Instead, you
can use the provideHttpClient function to provide the HttpClient service in your
application. Here is an example of how to use the provideHttpClient function to provide
the HttpClient service in your application:
import { ApplicationConfig, provideZoneChangeDetection } from
'@angular/core';
import { provideRouter } from '@angular/router';
HTTP Client
The HttpClient service is used to make HTTP requests to a server. It provides methods
for making GET, POST, PUT, DELETE, and other types of requests.
getData() {
return [Link]('[Link]
}
Back to top⤴️
Destroy Ref
The DestroyRef provider is a utility that allows Angular components to register cleanup
callbacks that are executed when the component is destroyed. This is useful for cleaning
up resources, such as subscriptions, timers, or other resources that need to be released
when the component is no longer in use.
@Component({
selector: 'my-component',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class MyComponent implements OnInit, OnDestroy {
ngOnInit() {
}
ngOnDestroy() {
// Register a destroy callback with the DestroyRef provider.
[Link](() => {
// Do any cleanup tasks here.
});
}
HTTP
Import HttpClient Module in Root Module -
@NgModule({
declarations: [
AppComponent
],
imports: [
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
HTTP GET
getData(){
return [Link]('url');
}
HTTP POST
sendData(data: any){
return [Link]('url', data);
}
HTTP PUT
updateData(data: any){
return [Link]('url', data);
}
HTTP PATCH
updateData(data: any){
return [Link]('url', data);
}
HTTP DELETE
deleteData(id: string){
return [Link](`url/${id}`);
}
HTTP Interceptor
Http Interceptors are a powerful feature provided by the @angular/common/http module.
They allow you to intercept and modify HTTP requests and responses in your Angular
application. With interceptors, you can perform various tasks such as authentication,
logging, error handling, and more. Interceptors provide a way to add global behavior to
your HTTP requests and responses, making it easier to implement common
functionalities across your application.
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
[Link]('Request started');
return [Link](req).pipe(
catchError((error) => {
[Link]('Request failed', error);
return throwError(error);
})
);
}
}
In angular v17, the HttpInterceptor interface has been deprecated in favor of the
HttpInterceptorFn type. The HttpInterceptorFn type is a function that takes a
HttpRequest and a HttpHandler and returns an Observable<HttpEvent>. Here is an
example of how to create an interceptor using the HttpInterceptorFn type:
@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, handler: HttpHandler):
Observable<HttpEvent<any>> {
[Link]('Request URL:', [Link]);
return [Link](req);
}
}
bootstrapApplication(AppComponent, {
providers: [
provideHttpClient(
withInterceptorsFromDi(), // Enable DI-based interceptors
),
{
provide: HTTP_INTERCEPTORS,
useClass: LoggingInterceptor,
multi: true
}
]
});
Using Observable
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
getData(): Observable<any> {
return [Link]<any>('utl');
}
Options—Headers/Params
Options—Observe/Response Type
Module
A module is a container for a group of related components, directives, pipes, and services.
It is used to organize an Angular application into cohesive blocks of functionality.
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
Back to top⤴️
Lazy loading
Lazy loading is a technique used to load modules only when they are needed. This can
help reduce the initial load time of the application by loading only the necessary modules.
@NgModule({
imports: [BrowserModule, FormsModule, AppRoutingModule],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule],
})
export class Page1RoutingModule {}
@NgModule({
imports: [CommonModule, Page1RoutingModule],
declarations: [Page1Component],
})
export class Page1Module {}
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule],
})
export class Page2RoutingModule {}
@NgModule({
imports: [CommonModule, Page2RoutingModule],
declarations: [Page2Component],
})
export class Page2Module {}
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet],
templateUrl: './[Link]',
styleUrl: './[Link]'
})
export class AppComponent {
// component logic here
}
⤴️
Back to top
Router
The Angular Router is a powerful tool that allows you to define navigation paths and
routes in your application. It enables you to navigate between different components and
views based on the URL path.
// [Link]
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
// [Link]
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UserDetailsComponent } from './user-details/[Link]';
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
To navigate to a route with a required parameter, you can use the Router service. For
example, in a component:
// [Link]
import { Router } from '@angular/router';
export class SomeComponent {
To define a route with an optional parameter, you can use a question mark (?) after the
parameter name. For example, in [Link]:
// [Link]
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { UserDetailsComponent } from './user-details/[Link]';
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Params
To access route parameters in a component, you can use the ActivatedRoute service. For
example, in a component:
// [Link]
import { ActivatedRoute } from '@angular/router';
Path Parameters:
Path parameters are used to extract data from the URL path. They are denoted by placing
a colon (“:”) before the parameter name in the route configuration. Path parameters are
part of the route path and can be accessed in the component associated with the route. For
example:
In this example, the “:id” parameter is a path parameter. The UserComponent can retrieve
the value of the “:id” parameter from the URL and use it to fetch user data.
Query Parameters:
Query parameters are used to pass data as key-value pairs in the URL query string. They
are denoted by placing a question mark (“?”) after the route path, followed by the
parameter name and value. Query parameters are not part of the route path but can be
accessed in the component associated with the route. For example:
In this example, the SearchComponent can access query parameters like “/search?
query=angular” or “/search?query=react” and use them to perform a search operation.
Optional Parameters:
Optional parameters are used to define route parameters that are not required. They are
denoted by placing a question mark (“?”) after the parameter name in the route
configuration. Optional parameters can be present or absent in the URL, and the
component associated with the route can handle both cases. For example:
Route Guards
Route guards are used to control access to routes in an Angular application. They allow
you to implement logic that determines whether a user is allowed to navigate to a
particular route or not. Route guards can be used to protect routes based on user
authentication, authorization, or other criteria.
There are four types of route guards in Angular:
CanActivate:
The CanActivate guard is used to determine whether a route can be activated or not. It is
typically used to check if a user is authenticated before allowing access to a route. The
guard returns a boolean value or an Observable or Promise that resolves to a boolean
value. If the guard returns true, the route is activated; if it returns false, the route is
blocked.
@Injectable()
export class AuthGuard implements CanActivate {
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
// Check if the user is authenticated
return true; // Allow access
}
}
canActivateFn:
The CanActivateFn guard is a function used to decide if a route can be accessed. It works
like the CanActivate guard but is a function instead of a class. It takes two arguments:
ActivatedRouteSnapshot and RouterStateSnapshot. The guard returns a boolean value or
an Observable or Promise that resolves to a boolean value. If the guard returns true, the
route is activated; if it returns false, the route is blocked.
import {
CanActivate,
ActivatedRouteSnapshot,
RouterStateSnapshot,
} from '@angular/router';
import { Observable } from 'rxjs';
CanActivateChild:
The CanActivateChild guard is similar to CanActivate but is used to protect child routes
of a parent route. It is applied to the parent route configuration and is triggered when any
child route is activated. The guard returns a boolean value or an Observable or Promise
that resolves to a boolean value.
@Injectable()
export class AuthGuard implements CanActivateChild {
canActivateChild(
childRoute: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
// Check if the user is authenticated
return true; // Allow access
}
}
CanDeactivate:
The CanDeactivate guard is used to determine whether a route can be deactivated or not.
It is typically used to prompt the user for confirmation before leaving a route with
unsaved changes. The guard returns a boolean value or an Observable or Promise that
resolves to a boolean value. If the guard returns true, the route is deactivated; if it returns
false, the route is not deactivated.
@Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<any> {
canDeactivate(
component: any,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState?: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
// Check if the user wants to leave the route
return confirm('Are you sure you want to leave?');
}
}
CanLoad:
The CanLoad guard is used to determine whether a lazy-loaded module can be loaded or
not. It is applied to the route configuration of a lazy-loaded module and is triggered when
the module is about to be loaded. The guard returns a boolean value or an Observable or
Promise that resolves to a boolean value. If the guard returns true, the module is loaded;
if it returns false, the module is not loaded.
@Injectable()
export class AuthGuard implements CanLoad {
canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
// Check if the user is authenticated
return true; // Allow loading
}
}
Back to top⤴️
Observables in Angular
An observable is a class that can be used to handle asynchronous data streams.
Observables are used to handle data that can arrive over time, such as data received from
a server, user input, or timed events.
Creating Observables
There are several ways to create observables in Angular:
Using the Observable Constructor: You can create an observable using the Observable
constructor and the new keyword. The constructor takes a function as an argument, which
is called when the observable is subscribed to.
Using the of Operator: You can create an observable from a list of values using the of
operator. The of operator emits each value in the list in sequence.
Subscribing to Observables
To receive data from an observable, you need to subscribe to it. The subscribe method is
used to subscribe to an observable and receive data emitted by the observable.
[Link]({
next: (value) => [Link](value),
error: (error) => [Link](error),
complete: () => [Link]('Complete')
});
Observables:
Observables are lazy, meaning they only execute when subscribed to.
Observables can emit multiple values over time.
Observables can be canceled using the unsubscribe method.
Observables can be transformed and combined using operators.
Observables are used for handling streams of data, such as user input, server
responses, and events.
Promises:
Back to top⤴️
Unsubscribe in Angular
In Angular, managing subscriptions is crucial to avoid memory leaks and improve the
performance of your application. Here are five ways to unsubscribe in Angular:
@Component({
selector: 'app-example',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class ExampleComponent implements OnDestroy {
private unsubscribe$ = new Subject<void>();
ngOnInit() {
// Subscribe to an observable
[Link](takeUntil([Link]$)).subscribe((data) => {
// Handle data
});
}
ngOnDestroy() {
[Link]$.next();
[Link]$.complete();
}
}
@Component({
selector: 'app-example',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class ExampleComponent implements OnDestroy {
private subscription: Subscription;
ngOnInit() {
// Assign the subscription
[Link] = [Link]((data) => {
// Handle data
});
}
ngOnDestroy() {
// Unsubscribe from the subscription
[Link]();
}
}
@Component({
selector: 'app-example',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class ExampleComponent implements OnDestroy {
private subscription;
ngOnInit() {
// Assign the subscription
[Link] = [Link]((data) => {
// Handle data
});
}
ngOnDestroy() {
// Unsubscribe from the subscription
[Link]();
}
}
@Component({
selector: 'app-example',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class ExampleComponent implements OnDestroy {
private subscriptions: Subscription[] = [];
ngOnInit() {
// Push the subscription to the array
[Link]([Link]((data) => {
// Handle data
}));
}
ngOnDestroy() {
// Unsubscribe from all subscriptions
[Link](subscription =>
[Link]());
}
}
Back to top ⤴️
Renderer2
Renderer2 is a utility class that provides methods to manipulate and interact with the
DOM (Document Object Model). It is used to perform operations such as creating,
modifying, and removing elements, applying styles, and listening to events.
@Component({
selector: 'app-example',
template: `
<button (click)="changeColor()">Change Color</button>
`
})
export class ExampleComponent {
constructor(private renderer: Renderer2, private el: ElementRef) { }
changeColor() {
const button = [Link]('button');
[Link](button, 'background-color', 'red');
}
}
JIT
Just-in-Time (JIT) is a type of compilation that compiles your app in the browser at
runtime. This is the default compilation mode for Angular applications.
Advantages of JIT
AOT
Ahead-of-Time (AOT) is a type of compilation that compiles your app at build time.
This mode is used to pre-compile your Angular application before deployment.
Advantages of AOT
Faster startup times as the browser only needs to execute the compiled code.
Improved performance due to optimized and pre-compiled templates.
Better security as the templates are already compiled and validated before
deployment.
Smaller bundle sizes since the templates are not included.
JIT vs AOT
Deferrable Views
Deferrable views can be used in component template to defer the loading of select
dependencies within that template.
@defer {
<large-component />
}
Meta tags
Title Service
import { BrowserModule, Title } from '@angular/platform-browser';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [Title],
bootstrap: [AppComponent]
})
export class AppModule { }
ngOnInit() {
[Link]("Learn Angular")
}
@Component({
template: `<h1>App Component</h1>`
})
export class AppComponent implements OnInit {
title = 'App Component';
constructor(private title:Title){
}
ngOnInit() {
[Link]("Learn Angular")
}
}
Title Service Example
// [Link]
import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
@NgModule({
declarations: [
AppComponent, HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [Title],
bootstrap: [AppComponent]
})
export class AppModule { }
// [Link]
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './[Link]';
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
// [Link]
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent {
title = 'Title Service Example';
constructor(private titleService:Title) {
}
ngOnInit() {
[Link]([Link]);
}
}
<ul>
<li><a [routerLink]="['/home']">Home</a> </li>
</ul>
<router-outlet></router-outlet>
// [Link]
import { Component, OnInit } from '@angular/core';
import { Title } from '@angular/platform-browser';
@Component({
template: `<h1>Home Component</h1>`
})
export class HomeComponent implements OnInit {
title = 'Home Component Title';
constructor(private titleService:Title){
}
ngOnInit() {
[Link]([Link]);
}
Dynamic Title
// [Link]
import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
@NgModule({
declarations: [
AppComponent, HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [Title],
bootstrap: [AppComponent]
})
export class AppModule { }
// [Link]
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './[Link]';
import { PParentComponent } from './[Link]';
import { ChildComponent } from './[Link]';
@NgModule({
imports: [[Link](routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
// [Link]
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { filter, map } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]']
})
export class AppComponent {
constructor(
private router: Router,
private activatedRoute: ActivatedRoute,
private titleService: Title
) { }
ngOnInit() {
[Link](
filter(event => event instanceof NavigationEnd),
)
.subscribe(() => {
var rt = [Link]([Link])
[Link](data => {
[Link](data);
[Link]([Link])})
})
getChild(activatedRoute: ActivatedRoute) {
if ([Link]) {
return [Link]([Link]);
} else {
return activatedRoute;
}
}
}
<ul>
<li><a routerLink="">Home</a> </li>
<li><a [routerLink]="['/parent']">Parent</a> </li>
<li><a [routerLink]="['/child']">Child</a> </li>
</ul>
<router-outlet></router-outlet>
// [Link]
import { Component, OnInit } from '@angular/core';
@Component({
template: `<h1>Home Component</h1>`
})
export class HomeComponent implements OnInit {
constructor(){
}
ngOnInit() {
}
}
// [Link]
import { Component, OnInit } from '@angular/core';
@Component({
template: `<h1>Parent Component</h1>
<router-outlet></router-outlet>
`
})
export class ParentComponent implements OnInit {
constructor(){
}
ngOnInit() {
}
// [Link]
import { Component, OnInit } from '@angular/core';
@Component({
template: `<h1>Child Component</h1>`
})
export class ChildComponent implements OnInit {
constructor(){
}
ngOnInit() {
}
Meta Service
import { BrowserModule, Meta } from '@angular/platform-browser';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [Meta],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Component, OnInit } from '@angular/core';
import { Meta, MetaDefinition } from '@angular/platform-browser';
@Component({
template: `<h1>App Component</h1>`
})
export class AppComponent implements OnInit {
title = 'App Component';
constructor(private metaService:Meta){
}
ngOnInit() {
[Link]( { name:'description',content:"Article
Description"});
}
[Link](
{ name: 'description', content: 'Article Description' },
{ name: 'robots', content: 'index,follow' },
{ property: 'og:title', content: 'Content Title for social media' }
);
[Link]("name='description'")
[Link]("name='robots'");
Back to top⤴️
Angular Signals
Angular Signals is a powerful system that provides detailed monitoring of state usage
within an application, enabling the framework to efficiently optimize rendering updates.
Writing Signals
Writable signals provide an API for updating their values directly. You create writable
signals by calling the signal function with the signal’s initial value:
Computed Signals
Computed signals are read-only signals that derive their value from other signals. You
define computed signals using the computed function and specifying a derivation:
Effects
Signals are useful because they notify interested consumers when they change. An effect
is an operation that runs whenever one or more signal values change. You can create an
effect with the effect function:
effect(() => {
[Link]('Count changed to:', count()); // Logs the count value whenever
it changes
});
constructor() {}
ngOnInit() {
// Optional logging for debugging displayedCount changes
// [Link]('Displayed count changed to:', [Link]());
}
incrementCount() {
[Link]([Link]() + 1);
}
decrementCount() {
[Link]((value) => [Link](0, value - 1));
}
}
Back to top ⤴️
Security
The security of an Angular application is a critical aspect that needs to be considered
during development. Here are some best practices to enhance the security of your
Angular application:
Use Angular’s built-in sanitization mechanisms to sanitize user input and prevent
script injection.
Avoid using unsafe methods like innerHTML and instead use Angular’s data binding
syntax to render dynamic content.
Use Angular’s built-in security features like Content Security Policy (CSP) to restrict
the sources of scripts and other resources that can be loaded by your application.
Enable strict mode in Angular templates to prevent template expressions from
executing arbitrary code.
Use Angular’s HttpClient module to make HTTP requests and automatically sanitize
responses to prevent XSS attacks.
HTML: Sanitizes user input for use in HTML contexts, such as rendering dynamic
content in templates.
Style: Sanitizes user input for use in CSS contexts, such as setting inline styles.
Script: Sanitizes user input for use in script contexts, such as event handlers and
script tags.
URL: Sanitizes user input for use in URL contexts, such as setting href attributes.
Resource URL: Sanitizes user input for use in resource URL contexts, such as
loading external resources.
Sanitization example
import { Component } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
@Component({
selector: 'app-root',
template: `<div [innerHTML]="safeHtml"></div>`
})
export class AppComponent {
safeHtml: SafeHtml;
To enable Trusted Types in an Angular application, you can configure the Trusted Types
policy using the TrustedTypesConfig token provided by Angular. The policy can specify
which types of values are considered trusted and enforce strict type checking on DOM
APIs.
const trustedTypesConfig = {
createPolicy: (name, policy) => {
return policy;
}
};
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [
{ provide: TRUSTED_TYPES_CONFIG, useValue: trustedTypesConfig }
],
bootstrap: [AppComponent]
})
export class AppModule { }
Use the AOT template compiler
The Angular Ahead-of-Time (AOT) template compiler compiles Angular templates at
build time, which helps prevent cross-site scripting (XSS) attacks by statically analyzing
the templates and generating optimized code. AOT compilation eliminates the need for
the browser to compile templates at runtime, reducing the risk of template injection
vulnerabilities.
To enable AOT compilation in an Angular application, you can use the ngc command to
compile the application ahead of time. AOT compilation is recommended for production
builds to improve performance, security, and compatibility with Content Security Policy
(CSP) restrictions.
ng build --aot
HTTP-level vulnerabilities
Angular applications can be vulnerable to various HTTP-level attacks, such as cross-site
request forgery (CSRF), cross-site scripting (XSS), and cross-site script inclusion (XSSI).
To protect against these vulnerabilities, you can use Angular’s built-in security features,
such as HttpClient XSRF/CSRF protection, custom cookie/header names, and disabling
XSRF protection.
@NgModule({
imports: [
HttpClientModule,
[Link]({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN'
})
]
})
@NgModule({
imports: [
HttpClientModule,
[Link]({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN'
})
]
})
@NgModule({
imports: [
HttpClientModule,
[Link]({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN'
})
]
})
Back to top⤴️
Angular Animations
Angular’s animation system is built on CSS functionality in order to animate any
property that the browser considers animatable. These properties includes positions, sizes,
transforms, colors, borders etc. The Angular modules for animations are
@angular/animations and @angular/platform-browser.
Animation Example
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './[Link]',
styleUrls: ['./[Link]'],
animations: [
trigger('fadeInOut', [
transition(':enter', [
style({ opacity: 0 }),
animate('1s', style({ opacity: 1 }))
]),
transition(':leave', [
animate('1s', style({ opacity: 0 }))
])
])
]
})
toggle() {
[Link] = ![Link];
}
}
<button (click)="toggle()">Toggle</button>
<div *ngIf="show" @fadeInOut>
<h1>Angular Animation Example</h1>
</div>
Back to top⤴️
Angular Universal
Angular Universal is a server-side rendering (SSR) solution for Angular applications that
allows you to render your application on the server and send the fully rendered HTML to
the client. This can improve performance, SEO, and user experience by reducing the time
to first contentful paint and enabling search engines to crawl and index your application.
To create an Angular Universal application, you can use the Angular CLI to generate a
new project with the Universal schematic.
ng new --ssr
To add Angular Universal to an existing Angular application, you can use the Angular
CLI to add the Universal schematic to the project.
ng add @angular/ssr
Back to top⤴️
Bootstrap
Bootstrap is a popular front-end framework for building responsive web applications. It
provides a set of CSS and JavaScript components that can be used to create modern and
mobile-friendly user interfaces.
Installing Bootstrap
npm install bootstrap
Importing Bootstrap
To use Bootstrap in an Angular application, you need to import the Bootstrap CSS file in
the styles array of the [Link] file.
"styles": [
"node_modules/bootstrap/dist/css/[Link]",
"src/[Link]"
]
Back to top⤴️
Angular Material
Angular Material is a UI component library for Angular applications that provides a set of
reusable and customizable components, such as buttons, cards, dialogs, and menus. It is
built on top of the Angular CDK (Component Dev Kit) and follows the Material Design
guidelines.
Installing Angular Material
ng add @angular/material
To use Angular Material in an Angular application, you need to import the required
modules in the [Link] file.
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatSliderModule
],
providers: [],
bootstrap: [AppComponent]
})
Back to top⤴️
Tailwind CSS
Tailwind CSS is a utility-first CSS framework that provides a set of pre-built utility
classes for styling web applications. It allows you to build custom designs by composing
utility classes together, rather than writing custom CSS styles.
To upgrade Tailwind CSS to the latest version, follow the steps outlined in the Tailwind
CSS Upgrade Guide. This guide provides detailed instructions on how to update your
Tailwind CSS configuration and resolve any breaking changes.
Back to top⤴️
PrimeNG
PrimeNG is a popular UI component library for Angular applications that provides a set
of rich and customizable components, such as data tables, calendars, dialogs, and charts.
It is built on top of the PrimeFaces library and follows the PrimeNG design guidelines.
Installing PrimeNG
npm install primeng
Importing PrimeNG
To use PrimeNG in an Angular application, you need to import the required styles and
modules in the [Link] file.
// [Link]
"styles": [
"node_modules/primeng/resources/themes/saga-blue/[Link]",
"node_modules/primeng/resources/[Link]",
"src/[Link]"
]
/* [Link] */
@import 'primeng/resources/themes/saga-blue/[Link]';
@import 'primeng/resources/[Link]';
Back to top⤴️
SPA
SPA (Single Page Application) is a web application that dynamically rewrites the current
page instead of loading entire new pages from the server, providing a fluid and
responsive user experience.
Advantages of SPA
Faster Load Times: Loads the initial page once; subsequent interactions update
dynamically.
Better User Experience: No full page reloads, allowing faster navigation and
smoother transitions.
Reduced Server Load: Less server load as only necessary data is fetched.
Improved SEO: Optimizable for search engines with server-side rendering and meta
tags.
Offline Support: Accessible offline using service workers and caching.
Mobile Support: Optimized for mobile with responsive design and touch gestures.
Scalability: Handles many users and interactions with performance optimizations
like lazy loading.
Back to top⤴️
PWA
Progressive Web Apps (PWAs) are web applications that provide a native app-like
experience to users, including offline support, push notifications, and home screen
installation. Angular provides built-in support for creating PWAs using the @angular/pwa
package.
Installing PWA
ng add @angular/pwa
Configuring PWA
To configure the PWA settings, you can modify the [Link] file in the src/
directory.
{
"index": "/[Link]",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/[Link]",
"/[Link]",
"/*.css",
"/*.js"
]
}
}
]
}
Building PWA
To build the PWA, you can run the ng build –prod command with the –
configuration=production flag.
Service Worker
The service worker is a script that runs in the background of the browser and handles
tasks such as caching assets, intercepting network requests, and providing offline support.
Angular’s service worker is generated automatically when you create a PWA using the
@angular/pwa package.
Features of PWA
Offline Support - The service worker caches assets and intercepts network requests to
provide offline support for the application.
Push Notifications - The service worker can receive push notifications from the server
and display them to the user.
Background Sync - The service worker can perform background sync tasks, such as
sending data to the server when the network connection is available.
Home Screen Installation - The service worker can prompt the user to install the
application on the home screen for quick access.
Back to top ⤴️
CLI Commands
Installing Angular CLI
Help
ng help
Check version
ng version
Create, build, and serve a new, basic Angular project cli command
ng new my-first-project
cd my-first-project
ng serve
ng new app-name
or
Component
ng g c component-name
ng generate component component-name
ng add
Build
ng build
Running project
ng serve
ng serve --port=portname
// example
ng serve --port=3000
ng serve --open
Update
ng update
Directive
Module
ng generate module module-name
ng g m module-name
Service
Routing Module
Pipe
ng g pipe pipe-name
Enum
ng g enum some-enum
Class
ng g cl my-class
Interface
ng g interface my-interface
Guard
ng g guard guard-name
Generate environments
ng generate environments
Version compatibility
Angular [Link] TypeScript RxJS
19.1.x ^18.19.1 || ^20.11.1 || ^22.0.0 >=5.5.0 <5.8.0 ^6.5.3 || ^7.4.0
19.0.x ^18.19.1 || ^20.11.1 || ^22.0.0 >=5.5.0 <5.7.0 ^6.5.3 || ^7.4.0
Angular [Link] TypeScript RxJS
18.1.x || 18.2.x ^18.19.1 || ^20.11.1 || ^22.0.0 >=5.4.0 <5.6.0 ^6.5.3 || ^7.4.0
18.0.x ^18.19.1 || ^20.11.1 || ^22.0.0 >=5.4.0 <5.5.0 ^6.5.3 || ^7.4.0
17.3.x ^18.13.0 || ^20.9.0 >=5.2.0 <5.5.0 ^6.5.3 || ^7.4.0
17.1.x || 17.2.x ^18.13.0 || ^20.9.0 >=5.2.0 <5.4.0 ^6.5.3 || ^7.4.0
17.0.x ^18.13.0 || ^20.9.0 >=5.2.0 <5.3.0 ^6.5.3 || ^7.4.0
For more detailed information on each version, you can visit the Angular Versions page.
Back to top ⤴️
Deploying an Angular Application
DEPLOYMENT TO PACKAGE
Firebase hosting ng add @angular/fire
Vercel vercel init angular
Netlify ng add @netlify-builder/deploy
GitHub pages ng add angular-cli-ghpages
NPM ng add ngx-deploy-npm
Amazon Cloud S3 ng add @jefiozie/ngx-aws-deploy
Back to top ⤴️
Imports
Angular Core
Angular Material
RxJS
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import { AsyncSubject } from 'rxjs/AsyncSubject';
import { Subscription } from 'rxjs/Subscription';
import { from } from 'rxjs';
import { fromEvent } from 'rxjs';
import { interval } from 'rxjs';
import { timer } from 'rxjs';
import { merge } from 'rxjs';
import { zip } from 'rxjs';
import { combineLatest } from 'rxjs';
import { concat } from 'rxjs';
import { forkJoin } from 'rxjs';
import { race } from 'rxjs';
import { map } from 'rxjs/operators';
import { filter } from 'rxjs/operators';
import { reduce } from 'rxjs/operators';
import { tap } from 'rxjs/operators';
import { catchError } from 'rxjs/operators';
import { retry } from 'rxjs/operators';
import { switchMap } from 'rxjs/operators';
import { take } from 'rxjs/operators';
import { debounceTime } from 'rxjs/operators';
import { distinctUntilChanged } from 'rxjs/operators';
import { scan } from 'rxjs/operators';
import { mergeMap } from 'rxjs/operators';
import { exhaustMap } from 'rxjs/operators';
import { concatMap } from 'rxjs/operators';
import { takeUntil } from 'rxjs/operators';
import { finalize } from 'rxjs/operators';
import { share } from 'rxjs/operators';
import { shareReplay } from 'rxjs/operators';
import { buffer } from 'rxjs/operators';
import { bufferCount } from 'rxjs/operators';
import { bufferTime } from 'rxjs/operators';
import { bufferToggle } from 'rxjs/operators';
import { bufferWhen } from 'rxjs/operators';
import { combineAll } from 'rxjs/operators';
import { concatAll } from 'rxjs/operators';
import { count } from 'rxjs/operators';
import { endWith } from 'rxjs/operators';
import { every } from 'rxjs/operators';
import { exhaust } from 'rxjs/operators';
import { first } from 'rxjs/operators';
import { groupBy } from 'rxjs/operators';
import { ignoreElements } from 'rxjs/operators';
import { isEmpty } from 'rxjs/operators';
import { last } from 'rxjs/operators';
import { max } from 'rxjs/operators';
import { mergeAll } from 'rxjs/operators';
import { min } from 'rxjs/operators';
import { pairwise } from 'rxjs/operators';
import { partition } from 'rxjs/operators';
import { pluck } from 'rxjs/operators';
Firebase
MVVM
MVVM stands for Model-View-ViewModel. It is a design pattern that separates the user
interface (View) from the business logic (Model) using a ViewModel. The ViewModel
acts as an intermediary between the View and the Model, providing data binding and
event handling.
MVC
MVC stands for Model-View-Controller. It is a design pattern that separates the user
interface (View) from the business logic (Model) using a Controller. The Controller acts
as an intermediary between the View and the Model, handling user input and updating the
Model.
TypeScript
TypeScript is JavaScript with syntax for types. TypeScript is a superset of JavaScript that
compiles to plain JavaScript. It is developed and maintained by Microsoft.
Rxjs
Reactive Extensions Library for JavaScript - RxJS is a library for reactive
programming using Observables, to make it easier to compose asynchronous or callback-
based code.
NgRx
NgRx is a Reactive libraries for Angular. It provides state management, side effects, and
route handling. It is inspired by Redux. It is a set of Angular libraries to help manage
state at scale in Angular applications.
NgXS
NgXS is a state management pattern + library for Angular. It acts as a single source of
truth for your application’s state, providing simple rules for predictable state mutations.
Back to top⤴️
Learn more from GitHub Repositories
Awesomw Angular
Angular JumpStart
Angular Interview Questions by Sudheerj
Angular Learning Resources
CodAffection
Bezkoder
Angular Interview Questions by Yonet
Angular Basics ( v14.x )
Contributing
Please read [Link] for details on our code of conduct, and the process for
submitting pull requests.
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
Angular
Stackblitz
Connect with me
Twitter
LinkedIn
Facebook
Instagram
YouTube
GitHub
Support
If you like this learning repository and find it useful, consider buying me a coffee or
sponsoring me through the GitHub Sponsor. Your support will help me to continue and
bring more exciting projects. Thank you!
Buy Me A Coffee
Sponsor Me