learn-angular
v2.2.0
Published
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.
Downloads
12
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.
Table of Contents
- Introduction
- Roadmap
- Configuration
- Components
- Data Binding
- Directives
- Pipes
- Decorators
- Life Cycle Hooks
- Forms
- Services
- Routing
- Lazy Loading
- HTTP Client
- Destroy Ref
- Http
- Module
- Router
- Route Parameter
- Observables
- Unsubscribe
- Renderer2
- JIT
- AOT
- Deferrable Views
- Meta Tags
- 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
- Standalone Components
- Angular Signals
- Angular Animations
- Angular Universal
- Bootstrap
- Angular Material
- Tailwind CSS
- PrimeNG
- PWA
- CLI Commands
- Version compatibility
- 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 web application framework developed by Google. It is used for building single-page web applications and dynamic web applications. Angular provides a set of tools and libraries for building modern web applications, including components, services, forms, routing, HTTP client, and more. Angular is built using TypeScript, a superset of JavaScript that adds static typing and other features to the language. Angular is known for its performance, scalability, and developer productivity.
Features of Angular
Component-Based Architecture - Angular is based on a component-based architecture, where components are the main building blocks of an application. Components are reusable, self-contained units of code that define the UI and behavior of a part of the application.
Two-Way Data Binding - Angular provides two-way data binding, which allows for automatic synchronization of data between the model and the view. This means that changes to the model are reflected in the view, and changes to the view are reflected in the model.
Dependency Injection - Angular uses dependency injection to provide components with the services they need. This allows for better modularity, testability, and reusability of code.
Routing - Angular provides a powerful routing system that allows for navigation between different views of an application. Routing is based on the URL of the application and allows for deep linking, lazy loading, and route guards.
Forms - Angular provides a rich set of tools for working with forms, including template-driven forms and reactive forms. Forms in Angular are based on the model-driven approach, where the form controls are bound to properties in the component's class.
HTTP Client - Angular provides an HTTP client module that allows for making HTTP requests to a server. The HTTP client module provides a simple API for working with RESTful APIs and handling responses.
Observables - Angular uses observables to handle asynchronous operations, such as HTTP requests and event handling. Observables are a powerful way to work with asynchronous data streams and provide a consistent way to handle events in an application.
TypeScript - Angular is built using TypeScript, a superset of JavaScript that adds static typing and other features to the language. TypeScript provides better tooling, error checking, and code completion, which makes it easier to build and maintain large applications.
Performance - Angular is designed for performance and scalability. It uses a virtual DOM to optimize rendering performance, and provides tools for lazy loading, tree shaking, and ahead-of-time compilation to reduce the size of the application and improve performance.
Mobile Support - Angular provides tools for building mobile applications, including responsive design, touch gestures, and mobile-specific features. Angular applications can be built as Progressive Web Apps (PWAs) and deployed to mobile devices using Cordova or Capacitor.
SEO Friendly - Angular provides tools for building SEO-friendly applications, including server-side rendering, pre-rendering, and meta tags. Angular applications can be optimized for search engines to improve visibility and ranking in search results.
Community Support - Angular has a large and active community of developers, who contribute to the framework, provide support, and share knowledge through blogs, forums, and social media. The Angular community is known for its helpfulness, inclusivity, and diversity.
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|
Angular vs React
Angular - Angular is a full-fledged framework that provides a complete solution for building web applications. It includes features like two-way data binding, routing, forms, HTTP client, and more. Angular is maintained by Google and has a large and active community of developers.
React - React is a JavaScript library for building user interfaces. It is focused on the view layer of an application and provides a simple and declarative way to build UI components. React is maintained by Facebook and has a large and active community of developers.
Comparison - Angular is a full-fledged framework that provides a complete solution for building web applications, while React is a library focused on building user interfaces. Angular provides features like two-way data binding, routing, forms, and HTTP client out of the box, while React is more flexible and allows developers to choose the tools and libraries they want to use.
When to use Angular - Angular is a good choice for building large and complex web applications that require a complete solution for building UI components, managing state, and handling data. Angular provides a set of tools and libraries that work well together and are designed to scale with the size of the application.
When to use React - React is a good choice for building user interfaces that are focused on the view layer of an application. React provides a simple and declarative way to build UI components and allows developers to choose the tools and libraries they want to use. React is a good choice for building small to medium-sized applications that require flexibility and customization.
SPA
SPA stands for Single Page Application. It is a web application or website that interacts with the user by dynamically rewriting the current page rather than loading entire new pages from the server. This approach allows for a more fluid and responsive user experience, as the page does not need to be reloaded each time the user interacts with it.
Advantages of SPA
Faster Load Times - SPAs load faster than traditional web applications because they only need to load the initial page once. Subsequent interactions with the application can be handled by updating the current page dynamically.
Better User Experience - SPAs provide a more fluid and responsive user experience because they do not need to reload the entire page each time the user interacts with it. This allows for faster navigation and smoother transitions between pages.
Reduced Server Load - SPAs reduce the load on the server because they do not need to fetch and render entire new pages each time the user interacts with the application. This can lead to cost savings and improved performance.
Improved SEO - SPAs can be optimized for search engines by using server-side rendering, pre-rendering, and meta tags. This allows search engines to index the content of the application and improve its visibility in search results.
Offline Support - SPAs can provide offline support by using service workers and caching strategies. This allows users to access the application even when they are offline or have a slow internet connection.
Mobile Support - SPAs can be optimized for mobile devices by using responsive design, touch gestures, and mobile-specific features. This allows the application to work well on a wide range of devices and screen sizes.
Scalability - SPAs are scalable and can handle a large number of users and interactions. They can be optimized for performance by using lazy loading, tree shaking, and ahead-of-time compilation to reduce the size of the application and improve performance.
Roadmap
Configuration
Prerequisites
- Node.js
Installation
Install the Angular CLI globally:
npm install -g @angular/cli
Check version
ng version
Create workspace:
# with standalone component
ng new [PROJECT NAME]
# without standalone component
ng new [PROJECT NAME] --standalone=false
Note: In version v17 and later, the standalone component is default enabled. In version v16 and earlier, the standalone component is disabled by default. You can enable or disable the standalone component using the --standalone
flag.
Navigate to the project directory:
cd [PROJECT NAME]
Run the application:
ng serve
Open the browser and navigate to http://localhost:4200/
.
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.
Providers - Defines the providers of the component's dependencies.
styles - Defines the inline styles for the component.
styleUrls - Defines an array of URLs of the stylesheets for the component.
template - Defines the HTML template for the component.
templateUrl - Defines the URL of the HTML template for the component.
Component Creation
Using Angular CLI
ng generate component [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].component.ts
Step 3 - Create a new HTML file for the component inside the new folder.
src/app/[component-name]/[component-name].component.html
Step 4 - Create a new CSS file for the component inside the new folder.
src/app/[component-name]/[component-name].component.css
Step 5 - Import the Component class from the @angular/core
module.
import { Component } from '@angular/core';
Step 6 - Decorate the class with the @Component
decorator.
@Component({
selector: 'app-[component-name]',
templateUrl: './[component-name].component.html',
styleUrls: ['./[component-name].component.css']
})
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.
export class [ComponentName]Component {
}
Step 9 - Import the component class in the app.module.ts
file.
import { [ComponentName]Component } from './[component-name]/[component-name].component';
Step 10 - Add the component to the declarations
array in the @NgModule
decorator.
declarations: [
AppComponent,
[ComponentName]Component
]
Step 11 - Use the component selector in the HTML template of the app.component.ts
file.
<app-[component-name]></app-[component-name]>
Step 12 - Run the application using the ng serve
command.
ng serve
Example
Creating the component files -
//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.component.html-->
<h1>Test Component</h1>
/*component.component.css*/
h1 {
color: red;
}
Importing the component in the app.module.ts file -
//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { TestComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Creating the inline Template & StyleUrls -
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: '<h1> {{title}} works </h1>',
styles: ['h1 { font-weight: bold; }']
})
export class AppComponent {
title = 'app';
}
Scope
The scope of a variable in Angular refers to the context in which the variable is defined and can be accessed. There are three main types of scope in Angular:
Global Scope - Variables defined in the global scope are accessible from anywhere in the application. They are defined outside of any function or block of code.
Local Scope - Variables defined in a function or block of code are accessible only within that function or block. They are not accessible outside of the function or block.
Component Scope - Variables defined in an Angular component are accessible within that component and its child components. They are not accessible outside of the component.
Global Scope
Variables defined in the global scope are accessible from anywhere in the application. They are defined outside of any function or block of code.
Example :
// Global Scope
let globalVariable = 'Global Variable';
function testFunction() {
console.log(globalVariable); // Output: Global Variable
}
testFunction();
Local Scope
Variables defined in a function or block of code are accessible only within that function or block. They are not accessible outside of the function or block.
Example :
function testFunction() {
// Local Scope
let localVariable = 'Local Variable';
console.log(localVariable); // Output: Local Variable
}
testFunction();
console.log(localVariable); // Error: localVariable is not defined
Component Scope
Variables defined in an Angular component are accessible within that component and its child components. They are not accessible outside of the component.
Example :
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// Component Scope
title = 'app';
}
<!--app.component.html-->
<h1>{{ title }}</h1>
View Encapsulation
View Encapsulation is a feature of Angular that allows you to control how styles are applied to components. By default, Angular uses Emulated View Encapsulation, which means that styles are scoped to the component and do not affect other components.
Emulated View Encapsulation
Emulated View Encapsulation is the default mode in Angular. In this mode, Angular emulates the shadow DOM to apply styles to components. This means that styles are scoped to the component and do not affect other components.
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';
}
Shadow DOM View Encapsulation
Shadow DOM View Encapsulation uses the native shadow DOM to apply styles to components. This means that styles are encapsulated within the shadow DOM and do not affect other components.
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';
}
None View Encapsulation
None View Encapsulation disables view encapsulation for the component. This means that styles are not scoped to the component and can affect other components.
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';
}
Component Communication
Component communication is the process of passing data between components in an Angular application. There are several ways to achieve component communication in Angular, including Input and 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 :
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() message: string;
}
<!--child.component.html-->
<p>{{ message }}</p>
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';
}
<!--parent.component.html-->
<app-child [message]="message"></app-child>
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 :
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<string>();
sendMessage() {
this.messageEvent.emit('Hello from child component');
}
}
<!--child.component.html-->
<button (click)="sendMessage()">Send Message</button>
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;
}
}
<!--parent.component.html-->
<app-child (messageEvent)="receiveMessage($event)"></app-child>
<p>{{ message }}</p>
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:
- From Component to View
- 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:
- Interpolation
- Property binding
- Class binding
- Style binding
- Attribute binding
Interpolation - This allows for embedding expressions in the HTML template. It is denoted by double curly braces ({{}}).
Example :
<h1>{{ firstText }} {{ lastText }}</h1>
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
firstText = 'Interpolation';
lastText = '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>
<button [disabled]="isDisabled">I am disabled</button>
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;
}
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 :
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;
}
}
<div [class.active]="isActive">This div is active.</div>
<button (click)="toggleActive()">Toggle Active</button>
.active {
background-color: yellow;
}
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 :
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
backgroundColor = 'red';
textColor = 'white';
}
<div [style.background-color]="backgroundColor">
<h1 [style.color]="textColor">Hello, world!</h1>
</div>
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 :
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;
}
<img [attr.src]="imageUrl" [attr.alt]="imageAlt">
<button [attr.disabled]="isButtonDisabled">Click me</button>
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:
- Event binding
- 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 :
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');
}
}
<h1>Event Binding Example</h1>
<button (click)="onClick()">Click me</button>
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 :
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name: string = '';
}
<input [(ngModel)]="name" placeholder="Enter your name">
<p>Your name is: {{name}}</p>
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.
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:
- ngModel
- ngModelChange
- 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.
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name: string = '';
}
<input [(ngModel)]="name" placeholder="Enter your name">
<p>Your name is: {{name}}</p>
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 :
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);
}
}
<input [(ngModel)]="name" (ngModelChange)="onNameChange($event)" placeholder="Enter your name">
<p>Your name is: {{name}}</p>
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 :
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);
}
}
<input [(ngModel)]="name" (change)="onNameChange($event.target.value)" placeholder="Enter your name">
<p>Your name is: {{name}}</p>
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:
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.
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.
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:
- NgIf
- NgFor
- 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 :
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
showElement = true;
}
<h1>ngIf Example</h1>
<div *ngIf="showElement">
This element will only be displayed if showElement is true.
</div>
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 :
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'];
}
<h1>ngFor Example</h1>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
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 :
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
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>
Attribute Directives
There are several built-in attribute directives in Angular, including:
- NgClass
- NgStyle
- 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 :
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
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;
}
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 :
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
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>
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 :
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
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>
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 :
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;
}
}
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 {}
<h1>Custom Directive Element</h1>
<div appCustomDirective>
This element will have a yellow background when the mouse is over it.
</div>
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 :
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
condition = true;
}
<h1>ngContainer Example</h1>
<div *ngIf="condition">
<ng-container>
<p>Content to be conditionally rendered</p>
<p>More content...</p>
</ng-container>
</div>
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 :
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
selectedTemplate: any;
}
<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>
<button (click)="selectedTemplate = myTemplate">Load Template</button>
ngContent - The ngContent
directive is used for content projection or transclusion. It allows you to create reusable components with customizable content.
Example :
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css'],
})
export class ChildComponent {}
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css'],
})
export class ParentComponent {}
<!-- Parent Component -->
<app-child>
<p>Content projected into the child component</p>
</app-child>
<!-- Child Component Template -->
<div>
<ng-content></ng-content>
</div>
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 :
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
selectedTemplate: any;
}
<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>
<button (click)="selectedTemplate = template1">Load Template 1</button>
<button (click)="selectedTemplate = template2">Load Template 2</button>
Pipes
A pipe takes in data as input and transforms it to a desired output.
Syntax:
{{ data | pipe }}
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.
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');
}
}
<h1>Date Pipe Example</h1>
<p>{{ date | date: 'shortDate' }}</p>
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 {}
Uppercase Pipe
The uppercase
pipe is used to transform a string to uppercase.
<h1>Upper Case Pipe Example</h1>
<p>{{ name | uppercase }}</p>
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Manthan Ank';
}
Lowercase Pipe
The lowercase
pipe is used to transform a string to lowercase.
<p>{{ name | lowercase }}</p>
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
name = 'Manthan Ank';
}
Currency Pipe
The currency
pipe is used to format a number as currency using the locale rules specified in the application.
<h1>Currency Pipe Example</h1>
<p>{{ price | currency }}</p>
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);
}
}
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 {}
Percent Pipe
The percent
pipe is used to format a number as a percentage.
<h1>Percent Pipe Example</h1>
<p>{{ percentage | percent }}</p>
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');
}
}
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 {}
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.
<p>{{ ['apple', 'banana', 'orange', 'mango'] | slice:1:3 }}</p>
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.
<p>{{ 123456.78 | number:'3.2-3' }}</p>
JSON Pipe
The json
pipe is used to transform a JavaScript object into a JSON string.
<p>{{data | json}}</p>
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>
// DataService.service.ts
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
@Injectable()
export class DataService {
private data$: Observable<string>;
constructor() {
// Simulating an asynchronous data source
this.data$ = of('Hello, async pipe!').pipe(
// Simulating delay
delay(2000)
);
}
getData(): Observable<string> {
return this.data$;
}
}
// ExampleComponent.component.ts
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { DataService } from './data.service';
@Component({
selector: 'app-example',
template: '<div>{{ data$ | async }}</div>',
})
export class ExampleComponent {
data$: Observable<string>;
constructor(private dataService: DataService) {
this.data$ = this.dataService.getData();
}
}
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.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'impurePipe',
pure: false,
})
export class ImpurePipe implements PipeTransform {
transform(value: any): any {
return value;
}
}
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.
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'My App';
}
<h1>{{ title }}</h1>
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.
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;
}
}
<div appCustomDirective>
This element will have a yellow background when the mouse is over it.
</div>
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.
import { Injectable } from '@angular/core';
@Injectable
export class DataService {
getData() {
return 'Hello, world!';
}
}
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();
}
}
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.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'customPipe',
})
export class CustomPipe implements PipeTransform {
transform(value: any, args?: any): any {
return value;
}
}
<h1>{{ data | customPipe }}</h1>
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.
import { NgModule } from '@angular/core';
@NgModule({
imports: [],
declarations: [],
providers: [],
bootstrap: [],
})
export class AppModule {}
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.
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() {}
}
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() {}
}
<p>{{ message }}</p>
<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';
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.
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<string>();
constructor() {}
ngOnInit() {}
sendMessage() {
this.messageEvent.emit('Hello from the child component!');
}
}
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);
}
}
<button (click)="sendMessage()">Send message</button>
<app-child (messageEvent)="handleMessage($event)"></app-child>
<h1>@Output Decorator Example</h1>
<app-parent></app-parent>
HostListener
The @HostListener
decorator is used to listen for events on the host element of a directive or component.
<h1>@HostListener Decorator Example</h1>
<p>Click the host element to trigger the 'click' event.</p>
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.
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<ElementRef>;
ngAfterContentInit() {
console.log(this.childButton1.nativeElement.textContent);
this.childButtons2.forEach((button) => {
console.log(button.nativeElement.textContent);
});
}
constructor() {}
ngOnInit() {}
}
<ng-content></ng-content>
<h1>@ContentChild Decorator Example</h1>
<app-parent></app-parent>
viewChild & viewChildren
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: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
@ViewChild('childButton1', { static: true }) childButton1: ElementRef;
@ViewChildren('childButton2') childButtons2: QueryList<ElementRef>;
ngAfterViewInit() {
console.log(this.childButton1.nativeElement.textContent);
this.childButtons2.forEach(button => {
console.log(button.nativeElement.textContent);
});
}
}
<h1>@viewChild & @viewChildren Example</h1>
<button #childButton1>Button 1</button>
<button #childButton2>Button 2</button>
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.
<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: './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;
}
}
<app-test [message]="'Hello World'"></app-test>
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.
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 n