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 روز
آرشیو پست ها
📄
Adding Initial DOM Rendering Transitions with @starting-style
#css #startingStyle
When a DOM element gets rendered from an HTML document or JavaScript code snippet, it gets rendered without any initial transition animation. In the past, we typically implemented these initial animations with dynamically switched CSS classes via JavaScript. Nowadays, we can use CSS animations for these situations, but the initial animation concept undoubtedly belongs to the CSS transitions feature. The `starting-style` at-rule lets you set initial styles for a CSS selector, so you can build up a transition animation for the initial rendering step:
button {
padding: 12px;
border: none;
border-radius: 4px;
font-size: 16px;
background-color: #bbb;
opacity: 1;
transform: scale(1);
transition: all 1s linear;
@starting-style {
opacity: 0;
transform: scale(0.5);
}
}
The above code snippet plays a transition animation when a button element gets rendered on the viewport. This transition works even though you dynamically create a new element with JavaScript.
📄 Defining Custom List Styles with
@counter-style
#css #counterStyle
We often use ordered and unordered lists in HTML documents. For customizing them, standard browsers offer various inbuilt list marker types via the list-style-type CSS property. You can extend these list styles or implement custom styles from scratch with the @counter-style at-rule.
Look at the following CSS code snippet:
@counter-style emojis {
system: cyclic;
symbols: 🔴 🟠 🟢;
suffix: ' ';
}
ul li {
list-style-type: emojis;
}
Moreover, it’s possible to customize existing inbuilt list styles with this at-rule:
@counter-style decimal-mod {
system: extends decimal;
prefix: '( ';
suffix: ' ): ';
pad: 2 '0';
}
ol li {
list-style-type: decimal-mod;
margin-bottom: 2px;
}
ol li::marker {
color: #780794;
}
The above CSS definition extends the default decimal list style by adding a prefix, suffix, and zero-padding.
📄 Modifying Printed Page Layouts with
@page
#css #page
Sometimes, users need to print web pages on physical papers for offline use. Also, some users print web pages as PDF documents to save for future use. Some web apps offer server-based features to generate paper-friendly PDF documents, but you can also print any web page using the browser’s native printing feature. The `page` CSS at-rule offers a way to customize page dimensions, orientation, and margins of printed pages without affecting the visible browser viewport. For example, the following CSS snippet sets a 1-inch margin and A4 landscape size for printed pages:
@page {
size: A4 landscape;
margin: 1in;
}
This at-rule comes with `:first`, `:blank`, `:left`, and `:right` pseudo-classes to select specific pages of the printed document. Browse the official MDN documentation to learn more details about `page`.
📄 Defining Animation Keyframes with
@keyframes
#css #keyframes
The modern CSS standard offers two solutions for creating smooth animations for DOM elements: 1. Switching CSS property values smoothly based on user interactions with the transition property. 2. Implementing keyframes-based advanced animations using the animation property. The second approach requires defining keyframes, so the @keyframes at-rule. Look at the following example:
<div class="board">CSS</div>
@keyframes board-anim {
0%, 85%, 100% {
filter: blur(0px);
}
90% {
filter: blur(5px) contrast(200%);
}
}
.board {
padding: 12px 50px;
font-size: 24px;
font-weight: bold;
background-color: #ff9d00;
color: #222;
display: inline-block;
animation: board-anim 3s infinite linear;
}🤓 Simplify Complexity with the Facade Design Pattern in TypeScript
#ts #patterns
Life is full of complexities. Even when we go about our everyday routines, we often interact with systems that are intricate behind the scenes but seem simple on the surface. Imagine driving a car. We don’t need to understand the nuances of its internal combustion engine or the intricacies of its transmission system. We just turn the key, press the gas pedal, and off we go! The same principle applies in the realm of software development, where we often encounter systems with daunting complexity. That’s where the Facade Design Pattern comes in handy. It provides a simplified, easy-to-use interface over a more complex underlying system, just like the controls in our car!✅ Article link 🎁 Code Link
📄 Understanding MIME Type Validators with Angular
#angular #fileReader
❗️What are MIME Type Validators?
MIME (Multipurpose Internet Mail Extensions) types are used to identify the type of content delivered in a file. MIME type validators, in the context of Angular, are functions or classes that verify whether a file’s MIME type matches the expected type.❗️Purpose of MIME Type Validation
The primary purpose of MIME type validation is to verify that the content of a file aligns with the expected format. This is especially crucial when dealing with sensitive file types, such as images, where incorrect MIME types could lead to rendering issues or security vulnerabilities.✅ Article link: https://enlear.academy/understanding-mime-type-validators-with-angular-3ff9bc2af559
📄 Passing CSS variables to Angular child +
:has
#angular #css #has
✅ Article link: https://medium.com/@bebrasmell/passing-css-variables-to-angular-child-7465646166eb🤓 REST API Design Best Practices
#api #restApi
There are different types of API protocols: REST — relies on a client/server approach that separates the front and back ends of the API and provides considerable flexibility in development and implementation. RPC — The remote procedural call (RPC) protocol sends multiple parameters and receives results. SOAP — Supports a wide range of communication protocols found across the internet, such as HTTP, SMTP, and TCP. WebSocket — Provides a way to exchange data between browser and server via a persistent connection.✅ Article link: https://medium.com/@techworldwithmilan/rest-api-design-best-practices-2eb5e749d428
📄 "Goodbye NgRx Facades. Hello Standalone Functions"
#angular #ngrx
Let’s list out the benefit of standalone functions: -- Decouple tight dependency between the component and the store. -- Simplifies CRUD operation with the store, by providing simple interfaces for the component to use to interact with the store. -- Reusability! -- No need to create a service(facade) to encapsulate NgRx logic. -- Stand alone functions are not tied to a class, meaning each can be imported and used individually. -- Reduces the need to inject multiple facade dependencies.✅ Article link: https://javascript.plainenglish.io/goodbye-ngrx-facades-hello-standalone-functions-7b7606c01659
📄 CSS variables in Angular: ng-deep is no longer needed
#angular #css #ngDeep
✅ Article link: https://medium.com/@maks-dolgikh/css-variables-in-angular-ng-deep-is-no-longer-needed-part-2-3ac60f8a4abc
📄 Master JavaScript Generators: 5 Practical Use Cases
#js #generators
Generators are these magical functions that you pause and resume, whenever you want — they don’t execute continuously.✅ Article link: https://javascript.plainenglish.io/javascript-generators-e4cdaa02839a
📄 Angular Internationalization Set-up in Existing Project
#angular #internationalization #i18n
Step 1: Install @angular/localize
$ ng add @angular/localize
Step 2: Update Angular JSON
Second screen
Step 3: Extract Messages
$ ng extract-i18n --output-path src/locale
This command will create XLF files in the specified locations (src/locale/messages.ar.xlf,src/locale/messages.fr.xlf)Step 4: Translate Messages
Translate the messages in each XLF file for the supported languages as mentioned in Angular Documentation here.Step 5: Build and Serve
$ ng build --localize
$ ng serve --configuration fr --port 4100 // Opens french version on port 4100
$ ng serve --configuration ar --port 4200 // Opens arabic version on port 4200
✅ Article link: https://levelup.gitconnected.com/angular-internationalization-set-up-in-existing-project-891dcf6cee95📄 Example of viewProviders for reusable controls
#angular #viewProviders #ControlContainer
✅ Article link: https://medium.com/medialesson/use-viewproviders-to-make-form-controls-reusable-in-angular-87be877bd102
🎁 Code link:
1 - Component link.
2 - Template link.
📄 Tracking an inactive user using RXJS
#angular #rxjs
User inactivity can be defined as a period during which a user does not interact with the application. Tracking this inactivity helps in various scenarios, such as optimizing resource usage, enhancing security, and providing a better user experience.
// inactivity.service.ts
import { Injectable } from '@angular/core';
import { Observable, fromEvent, timer } from 'rxjs';
import { mergeMap, mapTo } from 'rxjs/operators';
@Injectable({ providedIn: 'root'})
export class InactivityService {
public trackInactivity(
duration: number
): Observable<boolean> {
const mouseMove$ = fromEvent(document,'mousemove')
.pipe(mapTo(true));
const keyDown$ = fromEvent(document,'keydown')
.pipe(mapTo(true));
return timer(0, duration)
.pipe(
mergeMap(() => mouseMove$ || keyDown$)
);
}
}
✅ Article link: https://designtechworld.medium.com/angular-tracking-an-inactive-user-using-rxjs-in-built-and-custom-events-33d2e95fd167📄 Angular Custom Directives: TimeAgo Directive
#angular #directive
Creating a custom directive in Angular to display a time ago (relative time) can be useful for showing how long ago an event occurred. In this example, we’ll create a custom directive named appTimeAgo to display the time difference in a user-friendly format.
<p [appTimeAgo]="postDate"></p>📄 Angular Custom Directives: Disable Right-Click Directive
#angular #directive
Creating a custom directive in Angular to disable right-clicking can be useful in scenarios where you want to prevent users from accessing context menus or taking specific actions using the right mouse button. In this example, we’ll create a custom directive named `appDisableRightClick` to prevent right-clicking on elements.
import { Directive, HostListener } from '@angular/core';
@Directive({
selector: '[appDisableRightClick]'
})
export class DisableRightClickDirective {
constructor() {}
@HostListener('contextmenu', ['$event'])
onRightClick(event: Event): void {
event.preventDefault();
}
}
<div appDisableRightClick>
Right-clicking is disabled on this element.
</div>📄 Angular Custom Directives: Tooltip Directive
#angular #directive
Creating a custom directive in Angular to display tooltips can enhance user interfaces by providing additional information when users interact with specific elements. In this example, we’ll create a custom directive named appTooltip to show tooltips on hover.
<button
[appTooltip]="'Click me to learn more'"
>Learn More</button>📄 Angular Custom Directives: Copy to Clipboard Directive
#angular #directive
Creating a custom directive in Angular to allow users to copy content to the clipboard can enhance the usability of your application. In this example, we’ll create a custom directive named appCopyToClipboard to enable users to copy text when they click on an element.
import { Directive, Input, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appCopyToClipboard]'
})
export class CopyToClipboardDirective {
@Input() appCopyToClipboard: string;
constructor(private el: ElementRef) {}
@HostListener('click')
onClick() {
if (this.appCopyToClipboard) {
const textarea = document.createElement('textarea');
textarea.value = this.appCopyToClipboard;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
}
}
}
<button [appCopyToClipboard]="'Text to copy'">
Copy to Clipboard
</button>📄 Angular Custom Directives: Input Mask Directive
#angular #directive
Creating a custom directive in Angular to apply an input mask can help ensure that users enter data in a specific format. In this example, we’ll create a custom directive named appInputMask to format and validate an input as a phone number.
<input
type="text"
[appInputMask]="'(999) 999-9999'"
>