Angular 🇺🇦 - practical notes
Відкрити в Telegram
Angular - practical notes This group is for posting practical notes for Angular developers. Mostly all posts are for quick implementation https://t.me/angular_practical_notes (Commenting on posts only in ENG and UA langs here). Welcome!
Показати більше1 631
Підписники
Немає даних24 години
+17 днів
Немає даних30 днів
Архів дописів
📄 Angular Custom Directives: Custom Validation Directive
#angular #directive
A custom validation directive in Angular allows you to create your own custom validation logic for form controls. In this example, we’ll create a custom directive to validate that a password contains both letters and numbers. If the password doesn’t meet this criteria, we’ll mark the form control as invalid and display an error message. Here’s how you can create this custom validation directive
<input
type="password"
name="password"
[(ngModel)]="user.password"
#password="ngModel"
appPasswordValidator="[A-Za-z]+[0-9]+"
required
/>
<div *ngIf="
password.invalid
&& (password.dirty || password.touched)
">
<div *ngIf="password | hasError :'required'">
Password is required.
</div>
<div *ngIf="password | hasError :'passwordPattern'">
Password must contain letters and numbers.
</div>
</div>📄 Angular Interceptors: Timeout Interceptor
#angular #interceptor
A timeout interceptor can be used to set a maximum timeout for HTTP requests. It can be useful to prevent long-running requests from blocking your application.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
import { throwError, timer, Observable } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';
@Injectable()
export class TimeoutInterceptor implements HttpInterceptor {
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
): Observable<any> {
const timeoutDuration = 10000; // 10 seconds
return next.handle(request).pipe(
timeout(timeoutDuration),
catchError((error) => {
if (error.name === 'TimeoutError') {
// Handle timeout error here
console.error(
'Request timed out:', request.url
);
return throwError('Request timed out');
}
return throwError(error);
})
);
}
}📄 Angular Pipes: File Size Pipe
#angular #pipe
Converts a file size in bytes to a more human-readable format, such as KB, MB, or GB.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'fileSize' })
export class FileSizePipe implements PipeTransform {
transform(bytes: number): string {
if (isNaN(bytes) || bytes === 0) return '0 Bytes';
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(
Math.log(bytes) / Math.log(1024)
);
return `${parseFloat((bytes / Math.pow(1024, i)).toFixed(2))} ${sizes[i]}`;
}
}
Usage in an Angular template:
<p>{{ 1024 | fileSize }}</p>
<!-- Output: "1 KB" -->📄 Angular Interceptors: Loading Indicator Interceptor
#angular #interceptor
A loading indicator interceptor can be used to show and hide loading spinners or progress bars during HTTP requests, providing a better user experience.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
import { LoadingService } from './loading.service';
import { finalize } from 'rxjs/operators';
@Injectable()
export class LoadingInterceptor implements HttpInterceptor {
constructor(
private loadingService: LoadingService
) {}
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
) {
this.loadingService.showLoading();
return next.handle(request).pipe(
finalize(() => {
this.loadingService.hideLoading();
})
);
}
}📄 Angular Pipes: Phone Number Formatter Pipe
#angular #pipe
Formats a raw string of numbers into a well-structured phone number format (e.g., (555) 555–5555).
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'phoneNumberFormatter' })
export class PNFPipe implements PipeTransform {
transform(value: string): string {
if (!value || value.length !== 10) return value;
return `(${value.slice(0, 3)}) ${value.slice(3, 6)}-${value.slice(6)}`;
}
}
Usage in an Angular template:
<p>{{ '1234567890' | phoneNumberFormatter }}</p>
<!-- Output: "(123) 456-7890" -->📄 Angular Interceptors: Headers Interceptor
#angular #interceptor
A headers interceptor can be used to add custom headers to outgoing HTTP requests. This is often used to set headers like ‘Content-Type’ or include API keys.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
@Injectable()
export class HeadersInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<unknown>, next: HttpHandler) {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
'X-API-Key': 'your-api-key',
});
const headersRequest = request.clone({ headers });
return next.handle(headersRequest);
}
}📄 Angular Interceptors: Caching Interceptor
#angular #interceptor
A caching interceptor can be used to implement client-side caching for HTTP responses, reducing the number of unnecessary network requests.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpResponse,
HttpHeaders,
} from '@angular/common/http';
import { tap } from 'rxjs/operators';
@Injectable()
export class CacheInterceptor implements HttpInterceptor {
private cache = new Map<string, HttpResponse<unknown>>();
intercept(
request: HttpRequest<unknown>,
next: HttpHandler
) {
if (request.method !== 'GET') {
return next.handle(request);
}
const cachedResponse = this.cache.get(request.url);
if (cachedResponse) {
return of(cachedResponse);
}
return next.handle(request).pipe(
tap((event) => {
if (event instanceof HttpResponse) {
this.cache.set(request.url, event);
}
})
);
}
}📄 Resizable Columns in Angular Table
#angular #directive #ui_element
✅ Article link: https://levelup.gitconnected.com/how-to-create-resizable-columns-in-angular-scrollable-table-a-step-by-step-guide-5b8f766c1f60
🎁 Code link: https://stackblitz.com/edit/angular-6x5egd?file=src%2Fapp%2Fdirectives%2Fcolumn-resize.directive.ts
📄 Angular Pipes: Reverse String Pipe
#angular #pipe
This pipe reverses the characters of a string.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'reverseString' })
export class RSPipe implements PipeTransform {
transform(value: string): string {
if (!value) return value;
return value.split('').reverse().join('');
}
}
Usage in an Angular template:
<p>{{ 'Angular' | reverseString }}</p>
<!-- Output: "ralugnA" -->📄 Angular Interceptors: Logging Interceptor
#angular #interceptor
A logging interceptor can be used to log the details of HTTP requests and responses, which is helpful for debugging and monitoring.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpResponse,
} from '@angular/common/http';
import { tap } from 'rxjs/operators';
@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler) {
return next.handle(request).pipe(
tap((event) => {
if (event instanceof HttpResponse) {
console.log('HTTP Response:', event);
}
})
);
}
}Hello, friends!
As you can see, I'm a Ukrainian software engineer who tries to do volunteer fundraisers to support the Armed Forces of Ukraine. Sometimes it takes a lot of time and I am not able to maintain this channel for you. Please help me close these fundraisers because without the Ukrainian army there will be nothing Ukrainian. Thank you very much!
💵 FOR Ukraine:
https://send.monobank.ua/jar/5FDvaBP4zn
5375 4114 1222 8582
🌎 FOR ALL DONATS:
💵 SWIFT code: UNJSUAUKXXX
💵 PayPal: luckystudydanit@gmail.com
My profile with reports after closing fundraiser :
https://www.facebook.com/volunt2erua/
also all reports in our 🚀 channel:
https://t.me/toxicc_squad
📄 Downloading a PDF from a BASE64 String in Angular
#angular #pdf #base64
⚠️ The example is for presentation purposes only and can be refactored.
✅ Article link: https://kalanavw.medium.com/downloading-a-pdf-from-a-base64-string-in-angular-afe50fca1538
📄 Angular Pipes: Uppercase First Pipe
#angular #pipe
This pipe capitalizes the first letter of a string while keeping the rest in lowercase.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'uppercaseFirst' })
export class UppercaseFirstPipe implements PipeTransform {
transform(value: string): string {
if (!value) return value;
return value
.charAt(0)
.toUpperCase() + value.slice(1).toLowerCase();
}
}
Usage in an Angular template:
<p>{{ 'hello world' | uppercaseFirst }}</p>
<!-- Output: "Hello world" -->📄 Angular Interceptors: Error Handling Interceptor
#angular #interceptor
An error handling interceptor can be used to centralize error handling for HTTP requests. It can capture HTTP errors, log them, and perform appropriate actions like displaying error messages.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpErrorResponse,
} from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler) {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
// Handle and log the error here
console.error('HTTP Error:', error);
// Optionally rethrow the error to propagate it
return throwError(error);
})
);
}
}📄 Cross-Site Scripting (XSS) Attacks
#angular #xss
✅ Article link: https://rahuulmiishra.medium.com/mitigating-cross-site-scripting-xss-attacks-best-practices-and-code-examples-a5e4fd9d67a6
📄 Angular Interceptors: Authentication Interceptor
#angular #interceptor
An authentication interceptor is used to add authentication tokens to outgoing requests and handle authentication-related errors. This is essential for securing your application’s API requests.
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpHandler,
} from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler) {
const authToken = 'your-auth-token';
const authRequest = request.clone({
headers: request.headers.set('Authorization', `Bearer ${authToken}`),
});
return next.handle(authRequest);
}
}📄 Card Composite via @ViewChildren in Angular
#angular #decorator #ViewChildren
Imagine the following requirements for your Angular app: - Your customer wants a view that displays multiple cards at once. - A button at the top of the page should toggle the edit mode. - While in edit mode, all cards are editable at the same time. - As soon as you click “save” only those cards that actually have been edited are going to send a request to the server. - If you decide to discard the changes by clicking on “cancel” all cards should be reset to their initial state. This is a common scenario in any more sophisticated web application. Nevertheless, I just recently discovered a very handy way to handle those requirements in Angular. In this article I want to share my solution, leveraging the @ViewChildren property decorator to implement the Card Composite pattern.✅ Article link: https://blog.stackademic.com/card-composite-via-viewchildren-in-angular-aa3317f92f82
📄 Exploring the New
Object.groupBy Function in Chrome 117
#js #groupBy
✅ Article link: https://medium.com/@bhargavr445/exploring-the-new-object-groupby-function-in-chrome-117-028820848433📄 Transitioning to Angular 17’s New Control Flow Syntax
#angular #controlFlow
🚩 > Angular v17
✅ Article link: https://medium.com/@dimeloper/transitioning-to-angular-17s-new-control-flow-syntax-0555aa45f06f
📄 Change Detection in Angular
#angular #signals #cdr
4. Local Change Detection 🚩Angular 17
@Component({
selector: 'app-timer',
template: `<span>Last Updated: {{ lastUpdateInSeconds() | number:'1.0-0' }} Seconds</span> {{ logCd() }}`,
standalone: true,
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [DatePipe, DecimalPipe, AsyncPipe]
})
export class TimerComponent {
@Input() lastUpdate = new Date();
lastUpdateInSeconds = signal(0)
constructor() {
setInterval(() => {
this.lastUpdateInSeconds.set((new Date().getTime() - this.lastUpdate.getTime()) / 1_000);
}, 1000);
}
logCd() {
console.log('log from timer');
}
}
✅ Article link: https://medium.com/ngconf/local-change-detection-in-angular-410d82b38664