An open API service indexing awesome lists of open source software.

https://github.com/manthanank/learn-angular

Complete Guide to Learn Angular.
https://github.com/manthanank/learn-angular

angular learn learn-angular learning-angular rxjs

Last synced: 8 months ago
JSON representation

Complete Guide to Learn Angular.

Awesome Lists containing this project

README

          

# Learn Angular

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](https://img.shields.io/npm/dw/learn-angular)
![npm](https://img.shields.io/npm/dm/learn-angular)
![npm](https://img.shields.io/npm/dy/learn-angular)
![npm](https://img.shields.io/npm/dt/learn-angular)
![GitHub issues](https://img.shields.io/github/issues/manthanank/learn-angular)
![GitHub pull requests](https://img.shields.io/github/issues-pr/manthanank/learn-angular)
![GitHub](https://img.shields.io/github/license/manthanank/learn-angular)
![GitHub last commit](https://img.shields.io/github/last-commit/manthanank/learn-angular)
![GitHub top language](https://img.shields.io/github/languages/top/manthanank/learn-angular)
![GitHub repo size](https://img.shields.io/github/repo-size/manthanank/learn-angular)
![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/manthanank/learn-angular)
![GitHub contributors](https://img.shields.io/github/contributors/manthanank/learn-angular)
![GitHub forks](https://img.shields.io/github/forks/manthanank/learn-angular)
![GitHub stars](https://img.shields.io/github/stars/manthanank/learn-angular)
![GitHub watchers](https://img.shields.io/github/watchers/manthanank/learn-angular)

## Table of Contents

- [Introduction](#introduction)
- [Features of Angular](#features-of-angular)
- [Difference between AngularJS vs Angular](#difference-between-angularjs-vs-angular)
- [Angular vs React](#angular-vs-react)
- [Roadmap](#roadmap)
- [Configuration](#configuration)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Components](#components)
- [Three main building blocks](#three-main-building-blocks)
- [Component Creation](#component-creation)
- [Using Angular CLI](#using-angular-cli)
- [Manual Creation](#manual-creation)
- [Example](#example)
- [Scope](#scope)
- [View Encapsulation](#view-encapsulation)
- [Emulated View Encapsulation](#emulated-view-encapsulation)
- [Shadow DOM View Encapsulation](#shadow-dom-view-encapsulation)
- [None View Encapsulation](#none-view-encapsulation)
- [Component Communication](#component-communication)
- [Parent to Child](#parent-to-child)
- [Child to Parent](#child-to-parent)
- [Standalone Components](#standalone-components)
- [Data Binding](#data-binding)
- [One Way Binding](#one-way-binding)
- [Two Way Binding](#two-ways-binding)
- [Directives](#directives)
- [Structural Directives](#structural-directives)
- [Attribute Directives](#attribute-directives)
- [Custom Directives](#custom-directives)
- [Other Directives](#other-directives)
- [New Control Flow](#new-control-flow)
- [Pipes](#pipes)
- [Date Pipe](#date-pipe)
- [Uppercase Pipe](#uppercase-pipe)
- [Lowercase Pipe](#lowercase-pipe)
- [Currency Pipe](#currency-pipe)
- [Percent Pipe](#percent-pipe)
- [Slice Pipe](#slice-pipe)
- [Decimal/number Pipe](#decimalnumber-pipe)
- [JSON Pipe](#json-pipe)
- [Async Pipe](#async-pipe)
- [Decorators](#decorators)
- [Input](#input)
- [Output](#output)
- [HostListener](#hostlistener)
- [ContentChild & ContentChildren](#contentchild--contentchildren)
- [ViewChild & ViewChildren](#viewchild--viewchildren)
- [HostListener](#hostlistener)
- [ContentChild & ContentChildren](#contentchild--contentchildren)
- [ViewChild & ViewChildren](#viewchild--viewchildren)
- [Life Cycle Hooks](#life-cycle-hooks)
- [OnChanges](#onchanges)
- [OnInit](#oninit)
- [DoCheck](#docheck)
- [AfterViewInit](#afterviewinit)
- [AfterViewChecked](#afterviewchecked)
- [AfterContentInit](#aftercontentinit)
- [AfterContentChecked](#aftercontentchecked)
- [OnDestroy](#ondestroy)
- [Forms](#forms)
- [Template Driven Forms](#template-driven-forms)
- [Reactive Forms](#reactive-forms)
- [Services](#services)
- [Injectable Decorator](#injectable-decorator)
- [Dependency Injection](#dependency-injection)
- [Providers](#providers)
- [Routing](#routing)
- [Router Outlet](#router-outlet)
- [Router Link](#router-link)
- [Router Link Active](#router-link-active)
- [Router State](#router-state)
- [Router Events](#router-events)
- [Router Guards](#router-guards)
- [Lazy Loading](#lazy-loading)
- [HTTP Client](#http-client)
- [Destroy Ref](#destroy-ref)
- [Http](#http)
- [Module](#module)
- [Router](#router)
- [Route Parameter](#route-parameters)
- [Route Guards](#route-guards)
- [Observables](#observables-in-angular)
- [Creating Observables](#creating-observables)
- [Subscribing to Observables](#subscribing-to-observables)
- [Difference between Observables and Promises in Angular](#difference-between-observables-and-promises-in-angular)
- [Unsubscribe](#unsubscribe-in-angular)
- [Renderer2](#renderer2)
- [JIT](#jit)
- [AOT](#aot)
- [Deferrable Views](#deferrable-views)
- [Meta Tags](#meta-tags)
- [Title Service](#title-service)
- [Dynamic Title](#dynamic-title)
- [Meta Service](#meta-service)
- [Angular Signals](#angular-signals)
- [Security](#security)
- [Preventing cross-site scripting (XSS)](#preventing-cross-site-scripting-xss)
- [Angular's cross-site scripting security model](#angulars-cross-site-scripting-security-model)
- [Preventing cross-site scripting (XSS)](#preventing-cross-site-scripting-xss)
- [Angular's cross-site scripting security model](#angulars-cross-site-scripting-security-model)
- [Sanitization and security contexts](#sanitization-and-security-contexts)
- [Sanitization example](#sanitization-example)
- [Direct use of the DOM APIs and explicit sanitization calls](#direct-use-of-the-dom-apis-and-explicit-sanitization-calls)
- [Trusting safe values](#trusting-safe-values)
- [Content security policy](#content-security-policy)
- [Enforcing Trusted Types](#enforcing-trusted-types)
- [Use the AOT template compiler](#use-the-aot-template-compiler)
- [Server-side XSS protection](#server-side-xss-protection)
- [HTTP-level vulnerabilities](#http-level-vulnerabilities)
- [Cross-site request forgery](#cross-site-request-forgery)
- [HttpClient XSRF/CSRF security](#httpclient-xsrfcsrf-security)
- [Configure custom cookie/header names](#configure-custom-cookieheader-names)
- [Disabling XSRF protection](#disabling-xsrf-protection)
- [Cross-site script inclusion (XSSI)](#cross-site-script-inclusion-xssi)
- [Auditing Angular applications](#auditing-angular-applications)
- [Angular Animations](#angular-animations)
- [Installing Angular Animations](#installing-angular-animations)
- [Angular Universal](#angular-universal)
- [Creating an Angular Universal application](#creating-an-angular-universal-application)
- [Bootstrap](#bootstrap)
- [Installing Bootstrap](#installing-bootstrap)
- [Importing Bootstrap](#importing-bootstrap)
- [Angular Material](#angular-material)
- [Installing Angular Material](#installing-angular-material)
- [Importing Angular Material](#importing-angular-material)
- [Tailwind CSS](#tailwind-css)
- [Installing Tailwind CSS](#installing-tailwind-css)
- [Importing Tailwind CSS](#importing-tailwind-css)
- [PrimeNG](#primeng)
- [Installing PrimeNG](#installing-primeng)
- [Importing PrimeNG](#importing-primeng)
- [SPA](#spa)
- [Advantages of SPA](#advantages-of-spa)
- [PWA](#pwa)
- [Installing PWA](#installing-pwa)
- [Configuring PWA](#configuring-pwa)
- [Building PWA](#building-pwa)
- [Service Worker](#service-worker)
- [Features of PWA](#features-of-pwa)
- [CLI Commands](#cli-commands)
- [Version compatibility](#version-compatibility)
- [Deploying an Angular Application](#deploying-an-angular-application)
- [Imports](#imports)
- [TypeScript](#typescript)
- [RxJS](#rxjs)
- [Learn From GitHub Repositories](#learn-more-from-github-repositories)
- [Learn From Websites](#learn-more-from-websites)
- [Learn From Books](#learn-more-from-books)
- [Learn From YouTube Channels](#learn-from-youtube-channels)
- [Learn More From Blogs Sites](#learn-more-from-blogs-sites)
- [List of Online Editors/Compiler for Angular](#list-of-online-editorscompiler-for-angular)
- [List of Twitter Users to Follow](#list-of-twitter-users-to-follow)
- [List of LinkedIn Users to Follow](#list-of-linkedin-users-to-follow)
- [List of Discord Servers to Join](#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.

### Difference between AngularJS vs Angular

| AngularJS | Angular |
|-----|-----|
|Based on MVC Architecture|Based on Components|
|Uses JavaScript to build the application| Uses TypeScript to build the application|
|No Mobile Support|Mobile supports|
|Run on only client-side|Runs on both client-side as well as server-side|
|CLI not present|CLI present|
|No SEO Friendly|Seo Friendly|
|Performance is slow|Performance is fast|

[Back to top⤴️](#table-of-contents)

### 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.

- **React**: A JavaScript library by Facebook focused on building user interfaces. It provides a simple, declarative way to build UI components. Suitable for small to medium-sized applications requiring flexibility and customization.

**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⤴️](#table-of-contents)

## Roadmap

[Angular Roadmap](https://roadmap.sh/angular)

## Configuration

### Prerequisites

- Node.js
- NPM
- Angular CLI

### Installation

Install the Angular CLI globally:

```bash
npm install -g @angular/cli
```

If you are using `pnpm`, you can use the following command:

```bash
pnpm install -g @angular/cli
```

If you are using `yarn`, you can use the following command:

```bash
yarn global add @angular/cli
```

If you are using `bun`, you can use the following command:

```bash
bun install -g @angular/cli
```

If you want to install a specific version of the Angular CLI, you can use the following command:

```bash
npm install -g @angular/cli@version-number
```

If you have already installed the Angular CLI, you can update it to the latest version using the following command:

```bash
npm install -g @angular/cli@latest
```

Check version

```bash
ng version
```

Create a new Angular project: (Replace `[PROJECT NAME]` with your project name)

```bash
# with standalone component
ng new [PROJECT NAME]

# without standalone component
ng new [PROJECT NAME] --standalone=false

## 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

## with experimental zonless
ng new [PROJECT NAME] --experimental-zoneless
```

**Note**: In version v16 and earlier, there is no standalone component. In version v17 and later, the standalone component is default enabled. You can enable or disable the standalone component using the `--standalone` flag while creating a new project (In this repository, an example repository is created with the latest version of Angular).

Navigate to the project directory:

```bash
cd [PROJECT NAME]
```

Run the application:

```bash
ng serve
```

Open the browser and navigate to `http://localhost:4200/`.

Project structure(Version 16 and earlier):

```bash
[PROJECT NAME]
├── node_modules
├── src
│ ├── app
│ │ ├── app.component.css
│ │ ├── app.component.html
│ │ ├── app.component.spec.ts
│ │ ├── app.component.ts
│ │ ├── app.module.ts
│ │ ├── ...
│ ├── assets
│ │ ├── .gitkeep
│ │ └── ...
│ ├── index.html
│ ├── main.ts
│ ├── styles.css
│ ├── favicon.ico
│ └── ...
├── .editorconfig
├── .gitignore
├── angular.json
├── package.json
├── README.md
├── tsconfig.json
├── tslint.json
└── ...
```

Project structure(Version 17 and later):

```bash
[PROJECT NAME]
├── node_modules
├── public
│ ├── favicon.ico
│ └── ...
├── src
│ ├── app
│ │ ├── app.component.css
│ │ ├── app.component.html
│ │ ├── app.component.spec.ts
│ │ ├── app.component.ts
│ │ ├── app.config.ts
│ │ ├── app.routes.ts
│ │ └── ...
│ ├── index.html
│ ├── main.ts
│ ├── styles.css
│ └── ...
├── .editorconfig
├── .gitignore
├── angular.json
├── package.json
├── README.md
├── tsconfig.json
├── tslint.json
└── ...
```

[Back to top⤴️](#table-of-contents)

## 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.

### Three main building blocks

There are three main building blocks of an Angular component:

- Template
- Class
- Metadata

**Template** - Defines the layout and content of the View.

**Class** - Class provides the data & logic to the View.

**MetaData** - Metadata Provides additional information about the component to the Angular.

### Component metadata properties

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.

```typescript
selector: 'app-root'
```

**Providers** - Defines the providers of the component's dependencies.

```typescript
providers: [MyService]
```

**styles** - Defines the inline styles for the component.

```typescript
styles: ['h1 { color: red; }']
```

**styleUrls** - Defines an array of URLs of the stylesheets for the component.

```typescript
styleUrls: ['./app.component.css']
```

**template** - Defines the HTML template for the component.

```typescript
template: '

My Component

'
```

**templateUrl** - Defines the URL of the HTML template for the component.

```typescript
templateUrl: './app.component.html'
```

## Component Creation

### Using Angular CLI

```bash
ng generate component [component-name]

# or

ng g c [component-name]
```

### Manual Creation

**Step 1** - Create a new folder for the component inside the `src/app` folder.

```bash
src/app/[component-name]
```

**Step 2** - Create a new TypeScript file for the component inside the new folder.

```bash
src/app/[component-name]/[component-name].component.ts
```

**Step 3** - Create a new HTML file for the component inside the new folder.

```bash
src/app/[component-name]/[component-name].component.html
```

**Step 4** - Create a new CSS file for the component inside the new folder.

```bash
src/app/[component-name]/[component-name].component.css
```

**Step 5** - Import the Component class from the `@angular/core` module.

```typescript
import { Component } from '@angular/core';
```

**Step 6** - Decorate the class with the `@Component` decorator.

```typescript
@Component({
selector: 'app-[component-name]',
standalone: true,
templateUrl: './[component-name].component.html',
styleUrls: ['./[component-name].component.css']
})
```

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.

- selector - The selector for the component.
- templateUrl - The URL of the HTML template for the component.
- styleUrls - An array of URLs of the stylesheets for the component.

**Step 8** - Export the class.

```typescript
export class [ComponentName]Component {
// Component logic here
}
```

**Step 9** - Import the component class in the `app.module.ts` file.

```typescript
import { [ComponentName]Component } from './[component-name]/[component-name].component';
```

**Step 10** - Add the component to the `declarations` array in the `@NgModule` decorator.

```typescript
declarations: [
AppComponent,
[ComponentName]Component
]
```

If you created a standalone component, `app.module.ts` file is not required. You can import the component in the `app.component.ts` file.
as shown below.

```typescript
import { [ComponentName]Component } from './[component-name]/[component-name].component';

@Component({
selector: 'app-root',
standalone: true,
imports: [[ComponentName]Component],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})

export class AppComponent {
title = 'app';
}
```

**Step 11** - Use the component selector in the HTML template.

```typescript

```

**Step 12** - Run the application using the `ng serve` command.

```bash
ng serve

# or

ng serve --open
```

### Example

**Creating the component files (Version 16 and earlier)** -

```bash
//test-component.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'test-component',
templateUrl: './component.component.html',
styleUrls: ['./component.component.css']
})

export class TestComponent {
// Component logic here
}
```

```html

Test Component


```

```css
/*test.component.css*/
h1 {
color: red;
}
```

**Importing the component in the app.module.ts file** -

```typescript
//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { TestComponent } from './test-component.component';

@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```

**Importing the component in the app.component.ts file** -

```typescript
//app.component.ts
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { TestComponent } from './test-component.component';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent {
title = 'app';
}
```

```html

```

In Version 16 and earlier of Angular, there is no standalone component. You need to import the component in the `app.module.ts` file. If you created a non-standalone component, you will see no standalone property in the `@Component` decorator.

**Creating the component files (Version 17 and 18)** -

```bash
//test-component.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-test-component',
standalone: true,
templateUrl: './test-component.component.html',
styleUrls: ['./test-component.component.css']
})

export class TestComponent {
// Component logic here
}
```

```html

Test Component


```

```css
/*test.component.css*/
h1 {
color: red;
}
```

**Importing the component in the app.component.ts file** -

```typescript
//app.component.ts
import { Component } from '@angular/core';
import { TestComponent } from './test-component.component';

@Component({
selector: 'app-root',
imports: [TestComponent],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
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.

**Creating the component files (Version 19 and later)** -

```bash
//test-component.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-test-component',
templateUrl: './test-component.component.html',
styleUrls: ['./test-component.component.css']
})

export class TestComponent {
// Component logic here
}
```

```html

Test Component


```

```css
/*test.component.css*/
h1 {
color: red;
}
```

**Importing the component in the app.component.ts file** -

```typescript
//app.component.ts
import { Component } from '@angular/core';
import { TestComponent } from './test-component.component';

@Component({
selector: 'app-root',
imports: [TestComponent],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent {
title = 'app';
}
```

```html

```

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, `app.config.ts` file is created by default in version 17 and later of Angular. And `app.routes.ts` file is created by default in version 17 and later of Angular.

```typescript
// app.config.ts
import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
],
};
```

```typescript
// app.routes.ts
import { Routes } from '@angular/router';

export const routes: Routes = [];
```

You can import the component in the `app.component.ts` file and use the component selector in the HTML template.

**Creating the inline Template & StyleUrls** -

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
template: '

{{title}} works

',
styles: ['h1 { font-weight: bold; }']
})
export class AppComponent {
title = 'app';
}
```

[Back to top⤴️](#table-of-contents)

## Scope

In Angular, the scope of a variable determines where it can be accessed:

- **Global Scope**: Accessible anywhere in the application.
- **Local Scope**: Accessible only within a specific function or block.
- **Component Scope**: Accessible within a component and its child components.

### Global Scope

Accessible from anywhere in the application; defined outside any function or block.

Example :

```typescript
// Global Scope
let globalVariable = 'Global Variable';

function testFunction() {
console.log(globalVariable); // Output: Global Variable
}

testFunction();
```

Example in Angular :

```typescript
import { Component } from '@angular/core';

// Global Scope
let globalVariable = 'Global Variable';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent {
title = globalVariable;
}
```

```html

{{ title }}


```

### Local Scope

Accessible only within the function or block where defined.

Example :

```typescript
function testFunction() {
// Local Scope
let localVariable = 'Local Variable';
console.log(localVariable); // Output: Local Variable
}

testFunction();
console.log(localVariable); // Error: localVariable is not defined
```

Example in Angular :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent {
testFunction() {
// Local Scope
let localVariable = 'Local Variable';
console.log(localVariable); // Output: Local Variable
}
}
```

```html

Test Function
```

### Component Scope

Accessible within the component and its children.

Example :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})

export class AppComponent {
// Component Scope
title = 'app';
}
```

```html

{{ title }}


```

[Back to top⤴️](#table-of-contents)

## View Encapsulation

Controls how styles are applied to components. By default, Angular uses Emulated View Encapsulation, scoping styles to the component.

### Emulated View Encapsulation

Default mode in Angular, emulating shadow DOM to scope styles to the component.

```typescript
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.Emulated
})
export class AppComponent {
title = 'app';
}
```

[Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-xfz4uk?file=src%2Fmain.ts)

### Shadow DOM View Encapsulation

Uses native shadow DOM to encapsulate styles within the component, preventing them from affecting other components.

```typescript
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.ShadowDom
})
export class AppComponent {
title = 'app';
}
```

[Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-cc1rfn?file=src%2Fmain.ts)

### None View Encapsulation

Disables encapsulation; styles can affect other components.

```typescript
import { Component, ViewEncapsulation } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
encapsulation: ViewEncapsulation.None
})
export class AppComponent {
title = 'app';
}
```

[Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-gzsxag?file=src%2Fmain.ts)

[Back to top⤴️](#table-of-contents)

## 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 :

```typescript
import { Component, Input } from '@angular/core';

@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})

export class ChildComponent {
@Input() message: string;
}
```

```html

{{ message }}


```

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})

export class ParentComponent {
message = 'Hello from parent component';
}
```

```html

```

[Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-qqjcgn?file=src%2Fmain.ts)

### 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 :

```typescript
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})

export class ChildComponent {
@Output() messageEvent = new EventEmitter();

sendMessage() {
this.messageEvent.emit('Hello from child component');
}
}
```

```html

Send Message
```

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})

export class ParentComponent {
message: string;

receiveMessage($event) {
this.message = $event;
}
}
```

```html

{{ message }}


```

[Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-4qgrhm?file=src%2Fmain.ts)

[Back to top⤴️](#table-of-contents)

## 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 :

```typescript
import { Injectable } from '@angular/core';

@Injectable({
providedIn: 'root'
})

export class DataService {
message: string;

setMessage(message: string) {
this.message = message;
}

getMessage() {
return this.message;
}
}
```

```typescript
import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
selector: 'app-sibling1',
templateUrl: './sibling1.component.html',
styleUrls: ['./sibling1.component.css']
})

export class Sibling1Component {
message: string;

constructor(private dataService: DataService) {}

sendMessage() {
this.dataService.setMessage('Hello from sibling1 component');
}
}
```

```html

Send Message
```

```typescript
import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
selector: 'app-sibling2',
templateUrl: './sibling2.component.html',
styleUrls: ['./sibling2.component.css']
})

export class Sibling2Component {
message: string;

constructor(private dataService: DataService) {}

receiveMessage() {
this.message = this.dataService.getMessage();
}
}
```

```html

{{ message }}


Receive Message
```

[Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-uvqypy?file=src%2Fmain.ts)

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.

```typescript
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
providedIn: 'root'
})

export class DataService {
message = new Subject();

setMessage(message: string) {
this.message.next(message);
}
}
```

```typescript
import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
selector: 'app-sibling1',
templateUrl: './sibling1.component.html',
styleUrls: ['./sibling1.component.css']
})

export class Sibling1Component {
message: string;

constructor(private dataService: DataService) {}

sendMessage() {
this.dataService.setMessage('Hello from sibling1 component');
}
}
```

```html

Send Message
```

```typescript
import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
selector: 'app-sibling2',
templateUrl: './sibling2.component.html',
styleUrls: ['./sibling2.component.css']
})

export class Sibling2Component {
message: string;

constructor(private dataService: DataService) {}

ngOnInit() {
this.dataService.message.subscribe(message => {
this.message = message;
});
}
}
```

```html

{{ message }}


```

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.

```typescript
import { Component, ViewChild } from '@angular/core';
import { Sibling2Component } from './sibling2.component';

@Component({
selector: 'app-sibling1',
templateUrl: './sibling1.component.html',
styleUrls: ['./sibling1.component.css']
})

export class Sibling1Component {
@ViewChild(Sibling2Component) sibling2: Sibling2Component;

sendMessage() {
this.sibling2.message = 'Hello from sibling1 component';
}
}
```

```html

Send Message

```

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'app-sibling2',
templateUrl: './sibling2.component.html',
styleUrls: ['./sibling2.component.css']
})

export class Sibling2Component {
message: string;
}
```

```html

{{ message }}


```

[Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-nezkvf?file=src%2Fmain.ts)

[Back to top⤴️](#table-of-contents)

## 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

```typescript
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: `

Standalone Component


This is a self-contained component


`
})
export class StandaloneComponent {
// Component logic here
}
```

### Key Features of Standalone Components

- **Self-contained**: Declares its own dependencies through the imports array
- **No NgModule required**: Can be used without declaring in a module
- **Easier testing**: Simpler to test due to explicit dependencies
- **Better tree-shaking**: Enables more efficient bundle optimization
- **Simplified lazy-loading**: Can be lazy-loaded directly without module

### Using Standalone Components

```typescript
// Importing in another standalone component
@Component({
selector: 'app-parent',
standalone: true,
imports: [StandaloneComponent],
template: `

`
})
export class ParentComponent {}

// Bootstrapping a standalone component
import { bootstrapApplication } from '@angular/platform-browser';

bootstrapApplication(AppComponent, {
providers: [
// Root providers here
]
});
```

### Converting to Standalone

To convert an existing component to standalone:

1. Add `standalone: true` to the component decorator
2. Move dependencies from NgModule imports to component imports
3. Remove component declaration from NgModule
4. Import required dependencies directly in the component

[Back to top⤴️](#table-of-contents)

## 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:

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.

- **Two-way binding** - This allows for binding a property of an HTML element to a property in the component's class and vice-versa.

### One way binding

One-way binding allows for passing data from the component's class to the HTML template.

There are several ways to achieve one-way binding in Angular, including:

1. From Component to View
2. From View to Component

**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

**Interpolation** - This allows for embedding expressions in the HTML template. It is denoted by double curly braces ({{}}).

Example :

```html

{{ firstText }} {{ lastText }}


```

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
firstText = 'Interpolation';
lastText = 'Example';
}
```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-zu564w?file=src%2Fapp%2Fapp.component.ts)

**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 :

```html

I am disabled
```

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'Angular Property Binding Example';

isDisabled = true;
}
```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-vcpyoq?file=src/app/app.component.ts)

**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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
isActive = false;

toggleActive() {
this.isActive = !this.isActive;
}
}
```

```html

This div is active.

Toggle Active
```

```css
.active {
background-color: yellow;
}
```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-s1pkwg?file=src/app/app.component.ts)

**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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
backgroundColor = 'red';
textColor = 'white';
}
```

```html


Hello, world!



```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-w8nf7f?file=src/app/app.component.ts)

**attribute binding** - This allows for binding an attribute of an HTML element to a property in the component's class. It is denoted by square brackets ([]).

Example :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
imageUrl = 'https://example.com/image.jpg';
imageAlt = 'Example image';
isButtonDisabled = false;
}
```

```html

Click me
```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-bhqsgc?file=src/app/app.component.html)

**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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
onClick() {
console.log('Button was clicked');
}
}
```

```html

Event Binding Example


Click me
```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-kxuxsk?file=src/app/app.component.ts)

**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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})

export class AppComponent {
name: string = '';
}
```

```html

Your name is: {{name}}


```

**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 ``, ``, and `` 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](https://stackoverflow.com/a/51127794/14292971)

### 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)]`.

There are several ways to achieve two-way binding in Angular, including:

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.

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name: string = '';
}
```

```html

Your name is: {{name}}


```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-wrru3d?file=src/app/app.component.ts)

[Back to top⤴️](#table-of-contents)

**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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})

export class AppComponent {
name: string = '';

onNameChange(value: string) {
console.log('Name changed to:', value);
}
}
```

```html

Your name is: {{name}}


```

[Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-s43hdu?file=src%2Fmain.ts)

**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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})

export class AppComponent {
name: string = '';

onNameChange(value: string) {
console.log('Name changed to:', value);
}
}
```

```html

Your name is: {{name}}


```

[Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-s43hdu?file=src%2Fmain.ts)

[Back to top⤴️](#table-of-contents)

## 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:

1. **Structural Directives** - Structural directives are used to add or remove elements from the DOM based on a condition. They are denoted by an asterisk (*) before the directive name.

2. **Attribute Directives** - Attribute directives are used to change the appearance or behavior of an element. They are denoted by square brackets [] before the directive name.

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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
showElement = true;
}
```

```html

ngIf Example



This element will only be displayed if showElement is true.

```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-bajfgs?file=src%2Fapp%2Fapp.component.ts)

**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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})

export class AppComponent {
items = ['Item 1', 'Item 2', 'Item 3'];
}
```

```html

ngFor Example



  • {{ item }}


```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-sn3tgd?file=src%2Fapp%2Fapp.component.ts)

**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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
value = 1;
}
```

```html

ngSwitch Example



Case 1

Case 2

Case 3

Default case


```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-xm8ztp?file=src%2Fapp%2Fapp.component.ts)

### Attribute Directives

There are several built-in attribute directives in Angular, including:

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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
isHighlighted = true;
}
```

```html

ngClass Example



This element will have the 'highlighted' class if isHighlighted is true.

```

```css
.highlighted {
background-color: yellow;
}
```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-cn1fph?file=src%2Fapp%2Fapp.component.ts)

**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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
color = 'red';
}
```

```html

ngStyle Example



This element will have the color style set to the value of the color property.

```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-zcgf1h?file=src%2Fapp%2Fapp.component.ts)

**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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name: string;
}
```

```html

ngModel Example

Name:

```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-wrru3d?file=src%2Fapp%2Fapp.component.ts)

### 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 :

```typescript
import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
selector: '[appCustomDirective]',
})
export class CustomDirectiveDirective {
constructor(private el: ElementRef) {}

@HostListener('mouseenter') onMouseEnter() {
this.highlight('yellow');
}

@HostListener('mouseleave') onMouseLeave() {
this.highlight(null);
}

private highlight(color: string) {
this.el.nativeElement.style.backgroundColor = color;
}
}
```

```typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { CustomDirectiveDirective } from './custom-directive.directive';

@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent, CustomDirectiveDirective],
bootstrap: [AppComponent],
})
export class AppModule {}
```

```html

Custom Directive Element



This element will have a yellow background when the mouse is over it.

```

[Stackblitz Example](https://stackblitz.com/edit/angular-ivy-xyv8qw?file=src%2Fapp%2Fapp.component.ts)

[Back to top⤴️](#table-of-contents)

### Other directives

There are several other built-in directives in Angular, including:

- **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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})

export class AppComponent {
condition = true;
}
```

```html

ngContainer Example




Content to be conditionally rendered


More content...




```

[Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-zjr4xc?file=src%2Fmain.ts)

**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 :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})

export class AppComponent {
selectedTemplate: any;
}
```

```html

ngTemplate Example

This is a template


It can be reused in multiple places



Load Template
```

[Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-azqjxv?file=src%2Fmain.ts)

**ngContent** - The `ngContent` directive is used for content projection or transclusion. It allows you to create reusable components with customizable content.

Example :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css'],
})

export class ChildComponent {}
```

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css'],
})

export class ParentComponent {}
```

```html

Content projected into the child component

```

```html




```

[Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-8ddr3h?file=src%2Fmain.ts)

**ngTemplateOutlet** - The `ngTemplateOutlet` directive is used to render a template defined using ngTemplate. It allows you to dynamically render a template within a component's template.

Example :

```typescript
import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})

export class AppComponent {
selectedTemplate: any;
}
```

```html

ngTemplateOutlet Example

Template 1 content

Template 2 content

Load Template 1
Load Template 2
```

[Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-yerwcu?file=src%2Fmain.ts)

## New Control Flow

Conditionally display content with @if, @else-if and @else

```html
@if (a > b) {

{{a}} is greater than {{b}}


}
```

```html
@if (a > b) {
{{a}} is greater than {{b}}
} @else if (b > a) {
{{a}} is less than {{b}}
} @else {
{{a}} is equal to {{b}}
}
```

Repeat content with the @for block

```html
@for (item of items; track item.id) {
{{ item.name }}
}
```

Providing a fallback for @for blocks with the @empty block

```html
@for (item of items; track item.name) {

  • {{ item.name }}

  • } @empty {
  • There are no items.

  • }
    ```

    Conditionally display content with the @switch block

    ```html
    @switch (userPermissions) {
    @case ('admin') {

    }
    @case ('reviewer') {

    }
    @case ('editor') {

    }
    @default {

    }
    }
    ```

    [Back to top⤴️](#table-of-contents)

    ## Pipes

    A pipe takes in data as input and transforms it to a desired output.

    Syntax:

    ```text
    {{ data | pipe }}
    ```

    ```text
    Expression | pipeOperator[:pipeArguments]

    # Expression: is the expression, which you want to transform
    # | : is the Pipe Character
    # pipeOperator : name of the Pipe
    # pipeArguments: arguments to the Pipe
    ```

    ### 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.

    ```ts
    import { DatePipe } from '@angular/common';
    import { Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
    date = new Date();

    constructor(private datePipe: DatePipe) {}

    formatDate() {
    return this.datePipe.transform(this.date, 'shortDate');
    }
    }
    ```

    ```html

    Date Pipe Example


    {{ date | date: 'shortDate' }}


    ```

    ```ts
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';

    import { AppComponent } from './app.component';
    import { DatePipe } from '@angular/common';

    @NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [DatePipe],
    })
    export class AppModule {}
    ```

    [Stackblitz Example](https://stackblitz.com/edit/angular-ivy-fobnad?file=src%2Fapp%2Fapp.component.ts)

    ### Uppercase Pipe

    The `uppercase` pipe is used to transform a string to uppercase.

    ```html

    Upper Case Pipe Example


    {{ name | uppercase }}


    ```

    ```ts
    import { Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
    name = 'Manthan Ank';
    }
    ```

    [Stackblitz Example](https://stackblitz.com/edit/angular-ivy-hlmoxp?file=src%2Fapp%2Fapp.component.ts)

    ### Lowercase Pipe

    The `lowercase` pipe is used to transform a string to lowercase.

    ```html

    {{ name | lowercase }}


    ```

    ```ts
    import { Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
    name = 'Manthan Ank';
    }
    ```

    [Stackblitz Example](https://stackblitz.com/edit/angular-ivy-6gcdgx?file=src%2Fapp%2Fapp.component.ts)

    ### Currency Pipe

    The `currency` pipe is used to format a number as currency using the locale rules specified in the application.

    ```html

    Currency Pipe Example


    {{ price | currency }}


    ```

    ```ts
    import { CurrencyPipe } from '@angular/common';
    import { Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
    price = 100;

    constructor(private currencyPipe: CurrencyPipe) { }

    formatCurrency() {
    return this.currencyPipe.transform(this.price, 'USD', true);
    }
    }
    ```

    ```ts
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';

    import { AppComponent } from './app.component';
    import { CurrencyPipe } from '@angular/common';

    @NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [CurrencyPipe],
    })
    export class AppModule {}
    ```

    [Stackblitz Example](https://stackblitz.com/edit/angular-ivy-3fhhzz?file=src%2Fapp%2Fapp.component.ts)

    ### Percent Pipe

    The `percent` pipe is used to format a number as a percentage.

    ```html

    Percent Pipe Example


    {{ percentage | percent }}


    ```

    ```ts
    import { PercentPipe } from '@angular/common';
    import { Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
    percentage = 0.5;

    constructor(private percentPipe: PercentPipe) {}

    formatPercentage() {
    return this.percentPipe.transform(this.percentage, '2');
    }
    }
    ```

    ```ts
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';

    import { AppComponent } from './app.component';
    import { HelloComponent } from './hello.component';
    import { PercentPipe } from '@angular/common';

    @NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [PercentPipe],
    })
    export class AppModule {}
    ```

    [Stackblitz Example](https://stackblitz.com/edit/angular-ivy-tccybj?file=src%2Fapp%2Fapp.component.ts)

    ### 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.

    ```typescript

    {{ ['apple', 'banana', 'orange', 'mango'] | slice:1:3 }}


    ```

    [Stackblitz Example](https://stackblitz.com/edit/angular-ivy-q88gmm?file=src%2Fapp%2Fapp.component.ts)

    ### 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.

    ```html

    {{ 123456.78 | number:'3.2-3' }}


    ```

    [Stackblitz Example](https://stackblitz.com/edit/angular-ivy-7cwk1u?file=src%2Fapp%2Fapp.component.ts)

    ### JSON Pipe

    The `json` pipe is used to transform a JavaScript object into a JSON string.

    ```html

    {{data | json}}


    ```

    ```typescript
    import { Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    data = { name: 'Manthan Ank', age: 25 };
    }
    ```

    [Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-jgc252?file=src%2Fmain.ts)

    ### Async Pipe

    The `async` pipe is used to subscribe to an Observable or Promise and return the latest value it has emitted.

    ```html

    {{data$ | async}}


    ```

    ```typescript
    // DataService.service.ts
    import { Injectable } from '@angular/core';
    import { Observable, of } from 'rxjs';

    @Injectable()
    export class DataService {
    private data$: Observable;

    constructor() {
    // Simulating an asynchronous data source
    this.data$ = of('Hello, async pipe!').pipe(
    // Simulating delay
    delay(2000)
    );
    }

    getData(): Observable {
    return this.data$;
    }
    }
    ```

    ```typescript
    // ExampleComponent.component.ts
    import { Component } from '@angular/core';
    import { Observable } from 'rxjs';
    import { DataService } from './data.service';

    @Component({
    selector: 'app-example',
    template: '

    {{ data$ | async }}
    ',
    })
    export class ExampleComponent {
    data$: Observable;

    constructor(private dataService: DataService) {
    this.data$ = this.dataService.getData();
    }
    }
    ```

    [Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-iatcbn?file=src%2Fmain.ts)

    ### 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.

    ```typescript
    import { Pipe, PipeTransform } from '@angular/core';

    @Pipe({
    name: 'impurePipe',
    pure: false,
    })

    export class ImpurePipe implements PipeTransform {
    transform(value: any): any {
    return value;
    }
    }
    ```

    ```html

    {{ data | impurePipe }}


    ```

    ```typescript
    import { Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    data = 'Hello, world!';
    }
    ```

    ```typescript
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';

    import { AppComponent } from './app.component';

    @NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent, ImpurePipe],
    bootstrap: [AppComponent],
    })
    export class AppModule {}
    ```

    [Stackblitz Example](https://stackblitz.com/edit/stackblitz-starters-xy3hhp?file=src%2Fmain.ts)

    [Back to top⤴️](#table-of-contents)

    ## Decorators

    Decorators are design patterns used to isolate the modification or decoration of a class without modifying the source code.

    There are several built-in decorators in Angular, including:

    - **@Component**
    - **@Directive**
    - **@Injectable**
    - **@Pipe**
    - **@NgModule**
    - **@Input**
    - **@Output**
    - **@HostListener**
    - **@ContentChild**
    - **@ContentChildren**
    - **@ViewChild**
    - **@ViewChildren**

    ### Component

    The `@Component` decorator is used to define a new component in Angular.

    ```ts
    import { Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    title = 'My App';
    }
    ```

    ```html

    {{ title }}


    ```

    ```typescript
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';

    import { AppComponent } from './app.component';

    @NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    })

    export class AppModule {}
    ```

    ### Directive

    The `@Directive` decorator is used to define a new directive in Angular.

    ```ts
    import { Directive, ElementRef, HostListener } from '@angular/core';

    @Directive({
    selector: '[appCustomDirective]',
    })

    export class CustomDirective {
    constructor(private el: ElementRef) {}

    @HostListener('mouseenter') onMouseEnter() {
    this.highlight('yellow');
    }

    @HostListener('mouseleave') onMouseLeave() {
    this.highlight(null);
    }

    private highlight(color: string) {
    this.el.nativeElement.style.backgroundColor = color;
    }
    }
    ```

    ```html


    This element will have a yellow background when the mouse is over it.

    ```

    ```typescript
    import { NgModule } from '@angular/core';

    import { CustomDirective } from './custom.directive';

    @NgModule({
    declarations: [CustomDirective],
    })

    export class AppModule {}
    ```

    ### Injectable

    The `@Injectable` decorator is used to define a new service in Angular.

    ```ts
    import { Injectable } from '@angular/core';

    @Injectable
    export class DataService {
    getData() {
    return 'Hello, world!';
    }
    }
    ```

    ```ts
    import { Component } from '@angular/core';
    import { DataService } from './data.service';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    data: string;

    constructor(private dataService: DataService) {
    this.data = this.dataService.getData();
    }
    }
    ```

    ```typescript
    import { NgModule } from '@angular/core';

    import { AppComponent } from './app.component';

    @NgModule({
    declarations: [AppComponent],
    providers: [DataService],
    })

    export class AppModule {}
    ```

    ### Pipe

    The `@Pipe` decorator is used to define a new pipe in Angular.

    ```ts
    import { Pipe, PipeTransform } from '@angular/core';

    @Pipe({
    name: 'customPipe',
    })

    export class CustomPipe implements PipeTransform {
    transform(value: any, args?: any): any {
    return value;
    }
    }
    ```

    ```html

    {{ data | customPipe }}


    ```

    ```typescript
    import { NgModule } from '@angular/core';

    import { CustomPipe } from './custom.pipe';

    @NgModule({
    declarations: [CustomPipe],
    })

    export class AppModule {}
    ```

    ### NgModule

    The `@NgModule` decorator is used to define a new module in Angular.

    ```ts
    import { NgModule } from '@angular/core';

    @NgModule({
    imports: [],
    declarations: [],
    providers: [],
    bootstrap: [],
    })

    export class AppModule {}
    ```

    ```typescript
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';

    import { AppComponent } from './app.component';

    @NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    })

    export class AppModule {}
    ```

    ### Input

    The `@Input` decorator is used to pass data from a parent component to a child component.

    ```ts
    import { Component, Input, OnInit } from '@angular/core';

    @Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css']
    })
    export class ChildComponent implements OnInit {
    @Input() message: string;
    constructor() { }

    ngOnInit() {}

    }
    ```

    ```ts
    import { Component, OnInit } from '@angular/core';

    @Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.css'],
    })
    export class ParentComponent implements OnInit {
    parentMessage = 'Hello from the parent component!';
    constructor() {}

    ngOnInit() {}
    }
    ```

    ```html

    {{ message }}


    ```

    ```html

    ```

    ```html

    @Input Example

    ```

    ```typescript
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';

    import { AppComponent } from './app.component';
    import { RouterModule } from '@angular/router';
    import { ChildComponent } from './child/child.component';
    import { ParentComponent } from './parent/parent.component';

    @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.

    ```ts
    import { Component, EventEmitter, OnInit, Output } from '@angular/core';

    @Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css'],
    })
    export class ChildComponent implements OnInit {
    @Output() messageEvent = new EventEmitter();

    constructor() {}

    ngOnInit() {}

    sendMessage() {
    this.messageEvent.emit('Hello from the child component!');
    }
    }
    ```

    ```ts
    import { Component, OnInit } from '@angular/core';

    @Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.css'],
    })
    export class ParentComponent implements OnInit {
    constructor() {}

    ngOnInit() {}

    handleMessage(message: string) {
    console.log(message);
    }
    }
    ```

    ```html
    Send message
    ```

    ```html

    ```

    ```html

    @Output Decorator Example

    ```

    ### HostListener

    The `@HostListener` decorator is used to listen for events on the host element of a directive or component.

    ```html

    @HostListener Decorator Example


    Click the host element to trigger the 'click' event.


    ```

    ```ts
    import { Component, HostListener } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
    @HostListener('click')
    onClick() {
    console.log('The host element was clicked!');
    }
    }
    ```

    ### contentChild & contentChildren

    The `@ContentChild` and `@ContentChildren` decorators are used to query for content children in the component's view.

    ```ts
    import {
    Component,
    ContentChild,
    ContentChildren,
    ElementRef,
    OnInit,
    QueryList,
    } from '@angular/core';

    @Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.css'],
    })
    export class ParentComponent implements OnInit {
    @ContentChild('childButton1', { static: true }) childButton1: ElementRef;
    @ContentChildren('childButton2') childButtons2: QueryList;

    ngAfterContentInit() {
    console.log(this.childButton1.nativeElement.textContent);
    this.childButtons2.forEach((button) => {
    console.log(button.nativeElement.textContent);
    });
    }

    constructor() {}

    ngOnInit() {}
    }
    ```

    ```html

    ```

    ```html

    @ContentChild Decorator Example

    ```

    ### viewChild & viewChildren

    The `@ViewChild` and `@ViewChildren` decorators are used to query for view children in the component's view.

    ```ts
    import { Component, ElementRef, QueryList, ViewChild, ViewChildren } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css' ]
    })
    export class AppComponent {
    @ViewChild('childButton1', { static: true }) childButton1: ElementRef;
    @ViewChildren('childButton2') childButtons2: QueryList;

    ngAfterViewInit() {
    console.log(this.childButton1.nativeElement.textContent);
    this.childButtons2.forEach(button => {
    console.log(button.nativeElement.textContent);
    });
    }
    }
    ```

    ```html

    @viewChild & @viewChildren Example


    Button 1
    Button 2
    ```

    [Back to top⤴️](#table-of-contents)

    ## Life Cycle Hooks

    Angular provides a set of lifecycle hooks that give you visibility into key moments in the component's lifecycle.

    There are several lifecycle hooks in Angular, including:

    - **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.

    ```html


    Submit

    {{ message }}


    ```

    ```ts
    import {
    Component,
    Input,
    OnChanges,
    OnInit,
    SimpleChanges,
    } from '@angular/core';

    @Component({
    selector: 'app-test',
    templateUrl: './test.component.html',
    styleUrls: ['./test.component.css'],
    })
    export class TestComponent implements OnChanges {
    @Input() message: string;
    prevMessage: string;

    ngOnChanges(changes: SimpleChanges) {
    if (changes.message) {
    console.log(
    `message changed from ${changes.message.previousValue} to ${changes.message.currentValue}`
    );
    }
    }

    onSubmit() {
    this.prevMessage = this.message;
    }
    }
    ```

    ```html

    ```

    [Stackblitz Link](https://stackblitz.com/edit/angular-ivy-19r5mc?file=src/app/test/test.component.ts)

    ### OnInit

    It is called after Angular has initialized all data-bound properties of a directive/component. It is called only once after the first ngOnChanges.

    ```ts
    import { Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
    constructor() {}

    ngOnInit() {
    console.log('logged from ngOnInit');
    }
    }
    ```

    [Stackblits Link](https://stackblitz.com/edit/angular-ivy-hkmssz?file=src/app/app.component.html)

    ### 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.

    ```ts
    import { Component, DoCheck } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements DoCheck {
    ngDoCheck() {
    console.log('ngDoCheck Called');
    }
    }
    ```

    [Stackblitz Link](https://stackblitz.com/edit/angular-ivy-f5msas?file=src/app/app.component.ts)

    ### 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.

    ```ts
    import { AfterViewInit, Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements AfterViewInit{

    ngAfterViewInit(){
    console.log("after view init")
    }
    clickMe(){
    console.log("link clicked")
    }
    }
    ```

    ```html
    Click me
    ```

    [Stackblitz Link](https://stackblitz.com/edit/angular-wscf59?file=src/main.ts)

    ### AfterViewChecked

    It is called after Angular has checked the component's view and child views. It is called after ngAfterViewInit and every subsequent ngAfterContentChecked.

    ```ts
    import { AfterViewChecked, Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements AfterViewChecked {
    ngAfterViewChecked(){
    console.log("after view checked")
    }
    clickMe(){
    console.log("link clicked")
    }
    }
    ```

    ```html
    Click me
    ```

    [Stackblitz Link](https://stackblitz.com/edit/angular-wnwfnv?file=src/main.ts)

    ### 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.

    ```ts
    import { AfterContentInit, Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements AfterContentInit {
    ngAfterContentInit() {
    console.log('after content init');
    }
    clickMe() {
    console.log('clicked');
    }
    }
    ```

    ```html
    Click me
    ```

    [Stackblitz Link](https://stackblitz.com/edit/angular-qhy7cw?file=src/main.ts)

    ### 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.

    ```ts
    import { AfterContentInit, Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements AfterContentInit {
    ngAfterContentChecked() {
    console.log('after content init');
    }
    clickMe() {
    console.log('clicked');
    }
    }
    ```

    ```html
    Click me
    ```

    [Stackblitz Link](https://stackblitz.com/edit/angular-ryx2uh?file=src/main.ts)

    ### 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.

    ```ts
    import { Component, OnDestroy, OnInit } from '@angular/core';
    import { Subscription } from 'rxjs';
    import { of } from 'rxjs';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements OnInit, OnDestroy {
    private subscription: Subscription;

    ngOnInit() {
    const someObservable = of(1, 2, 3);
    this.subscription = someObservable.subscribe((data) => {
    console.log(data);
    });
    }

    ngOnDestroy() {
    this.subscription.unsubscribe();
    }
    }
    ```

    [Stackblitz Link](https://stackblitz.com/edit/angular-ivy-urqida?file=src/app/app.module.ts)

    [Back to top⤴️](#table-of-contents)

    ## 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.

    ```html


    Submit

    ```

    ```ts
    import { Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })
    export class AppComponent {
    onSubmit(form: NgForm) {
    console.log(form.value);
    }
    }
    ```

    ### Reactive Forms

    Reactive forms are created programmatically using form controls and form groups. They provide more control and flexibility compared to template-driven forms.

    ```ts
    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    name: ['', Validators.required],
    email: ['', Validators.email],
    });
    }

    onSubmit() {
    console.log(this.form.value);
    }
    }
    ```

    ```html



    Submit

    ```

    [Back to top⤴️](#table-of-contents)

    Set Value in Template Driven forms in Angular

    ```html


    Submit

    ```

    ```ts
    import { Component } from '@angular/core';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    onSubmit(form: NgForm) {
    form.setValue({ name: 'John' });
    }
    }
    ```

    [Back to top⤴️](#table-of-contents)

    FormBuilder in Reactive Forms

    ```ts
    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    name: ['', Validators.required],
    email: ['', Validators.email],
    });
    }

    onSubmit() {
    console.log(this.form.value);
    }
    }
    ```

    SetValue & PatchValue in Angular

    ```ts
    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup } from '@angular/forms';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    name: '',
    email: '',
    });

    this.form.setValue({
    name: 'John',
    email: 'john.doe@gmail.com',
    });

    this.form.patchValue({
    name: 'Jane',
    });
    }

    onSubmit() {
    console.log(this.form.value);
    }
    }
    ```

    StatusChanges in Angular Forms

    ```ts
    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup } from '@angular/forms';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    name: '',
    email: '',
    });

    this.form.statusChanges.subscribe((status) => {
    console.log(status);
    });
    }

    onSubmit() {
    console.log(this.form.value);
    }
    }
    ```

    ValueChanges in Angular Forms

    ```ts
    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup } from '@angular/forms';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    name: '',
    email: '',
    });

    this.form.valueChanges.subscribe((value) => {
    console.log(value);
    });
    }

    onSubmit() {
    console.log(this.form.value);
    }
    }
    ```

    FormControl

    ```ts
    import { Component } from '@angular/core';
    import { FormControl } from '@angular/forms';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    name = new FormControl('');

    onSubmit() {
    console.log(this.name.value);
    }
    }
    ```

    FormGroup

    ```ts
    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup } from '@angular/forms';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    name: '',
    email: '',
    });
    }

    onSubmit() {
    console.log(this.form.value);
    }
    }
    ```

    FormArray Example

    ```ts
    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    name: '',
    emails: this.fb.array([]),
    });
    }

    get emails() {
    return this.form.get('emails') as FormArray;
    }

    addEmail() {
    this.emails.push(this.fb.control(''));
    }

    removeEmail(index: number) {
    this.emails.removeAt(index);
    }

    onSubmit() {
    console.log(this.form.value);
    }
    }
    ```

    ```html





    Remove


    Add Email
    Submit

    ```

    Build Dynamic or Nested Forms using FormArray

    ```ts
    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    name: '',
    addresses: this.fb.array([]),
    });
    }

    get addresses() {
    return this.form.get('addresses') as FormArray;
    }

    addAddress() {
    this.addresses.push(
    this.fb.group({
    street: '',
    city: '',
    state: '',
    zip: '',
    })
    );
    }

    removeAddress(index: number) {
    this.addresses.removeAt(index);
    }

    onSubmit() {
    console.log(this.form.value);
    }
    }
    ```

    ```html









    Remove



    Add Address
    Submit

    ```

    SetValue & PatchValue in FormArray

    ```ts
    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    name: '',
    addresses: this.fb.array([]),
    });

    this.form.setValue({
    name: 'John',
    addresses: [
    { street: '123 Main St', city: 'Anytown', state: 'CA', zip: '12345' },
    { street: '456 Elm St', city: 'Othertown', state: 'NY', zip: '67890' },
    ],
    });

    this.form.patchValue({
    name: 'Jane',
    });
    }

    get addresses() {
    return this.form.get('addresses') as FormArray;
    }

    addAddress() {
    this.addresses.push(
    this.fb.group({
    street: '',
    city: '',
    state: '',
    zip: '',
    })
    );
    }

    removeAddress(index: number) {
    this.addresses.removeAt(index);
    }

    onSubmit() {
    console.log(this.form.value);
    }
    }
    ```

    ```html









    Remove



    Add Address
    Submit

    ```

    Select Options Dropdown

    ```ts
    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup } from '@angular/forms';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    name: '',
    gender: '',
    });
    }

    onSubmit() {
    console.log(this.form.value);
    }
    }
    ```

    ```html



    Male
    Female

    Submit

    ```

    Typed Forms in Angular

    ```ts
    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup } from '@angular/forms';

    interface User {
    name: string;
    email: string;
    }

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    name: '',
    email: '',
    });
    }

    onSubmit() {
    console.log(this.form.value);
    }
    }
    ```

    ```html



    Submit

    ```

    FormArray in Angular

    ```ts
    import { Component } from '@angular/core';
    import { FormBuilder, FormGroup } from '@angular/forms';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    form: FormGroup;

    constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
    name: '',
    email: '',
    });
    }

    onSubmit() {
    console.log(this.form.value);
    }
    }
    ```

    ```html



    Submit

    ```

    ## 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.

    ```ts
    import { Injectable } from '@angular/core';

    @Injectable
    export class DataService {
    getData() {
    return 'Data from the service';
    }
    }
    ```

    ```ts
    import { Component } from '@angular/core';
    import { DataService } from './data.service';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    data: string;

    constructor(private dataService: DataService) {
    this.data = this.dataService.getData();
    }
    }
    ```

    [Back to top⤴️](#table-of-contents)

    ### Injectable Decorator

    The `@Injectable` decorator is used to define a service class that can be injected into other components or services.

    ```ts
    import { Injectable } from '@angular/core';

    @Injectable
    export class DataService {
    getData() {
    return 'Data from the service';
    }
    }
    ```

    [Back to top⤴️](#table-of-contents)

    ### 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.

    ```ts
    import { Injectable } from '@angular/core';

    @Injectable
    export class DataService {
    getData() {
    return 'Data from the service';
    }
    }
    ```

    ```ts
    import { Component } from '@angular/core';
    import { DataService } from './data.service';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    data: string;

    constructor(private dataService: DataService) {
    this.data = this.dataService.getData();
    }
    }
    ```

    Using `@inject` decorator is an alternative way to inject dependencies into a class.

    ```typescript
    import { Component } from '@angular/core';
    import { DataService } from './data.service';

    @Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    })

    export class AppComponent {
    data: string;
    private dataService = inject(DataService);

    constructor() {
    this.data = this.dataService.getData();
    }
    }
    ```

    [Back to top⤴️](#table-of-contents)

    ### 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.

    ```ts
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { FormsModule } from '@angular/forms';

    import { AppComponent } from './app.component';
    import { DataService } from './data.service';

    @NgModule({
    imports: [BrowserModule, FormsModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent],
    providers: [DataService],
    })

    export class AppModule {}
    ```

    [Back to top⤴️](#table-of-contents)

    ## 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.

    ```ts
    import { NgModule } from '@angular/core';
    import { RouterModule, Routes } from '@angular/router';

    const routes: Routes = [];

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

    export class AppRoutingModule {}
    ```

    ```typescript
    import { Routes } from '@angular/router';

    export const routes: Routes = [];
    ```

    ```typescript
    import { Applica