Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

AngularJS Hosting Europe - HostForLIFE.eu :: Using ngx-webcam to Implement Webcam Image Capture in Angular

clock October 18, 2023 07:09 by author Peter

In this blog post, we'll go over how to build an Angular application that allows users to directly capture photographs from their webcams. To accomplish this, we'll use the ngx-webcam library, which includes webcam capabilities and covers the library's installation as well as the basic setup of the Angular application in the project.


Step 1: Begin by creating a new Angular project.

If you haven't previously, enter the following command in your terminal or command line to install the Angular CLI globally:
npm install -g @angular/cli

Make a new Angular project as follows:
ng new CaptureImage

Go to the project directory:
cd D:\Angular\Project\CaptureImage

Step 2: Set up the ngx-webcam Library.
npm install ngx-webcam

Step 3: Incorporate ngx-webcam into your Angular app.
Import the WebcamModule from ngx-webcam into the src/app/app.module.ts file:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ImageWebcamComponent } from './image-webcam/image-webcam.component';
import { WebcamModule } from 'ngx-webcam';

@NgModule({
  declarations: [
    AppComponent,
    ImageWebcamComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    WebcamModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Step 4: Make a Webcam Component
Make a new component to manage webcam functionality. Run the following command in your terminal:
ng generate component image-webcam

Open src/app/image-webcam/image-webcam.component.ts and add the following logic to capture images:

import { Component } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import { WebcamImage, WebcamInitError, WebcamUtil } from 'ngx-webcam';
@Component({
  selector: 'app-image-webcam',
  templateUrl: './image-webcam.component.html',
  styleUrls: ['./image-webcam.component.css']
})
export class ImageWebcamComponent {

  private trigger: Subject<any> = new Subject();
  webcamImage: any;
  private nextWebcam: Subject<any> = new Subject();

  sysImage = '';

  ngOnInit() {}

  public getSnapshot(): void {
    this.trigger.next(void 0);
  }

  public captureImg(webcamImage: WebcamImage): void {
    this.webcamImage = webcamImage;
    this.sysImage = webcamImage!.imageAsDataUrl;
    console.info('got webcam image', this.sysImage);
  }

  public get invokeObservable(): Observable<any> {
    return this.trigger.asObservable();
  }

  public get nextWebcamObservable(): Observable<any> {
    return this.nextWebcam.asObservable();
  }
}

Add the following code to src/app/image-webcam/image-webcam.component.html.

<div class="container mt-5">
  <h2>Angular Webcam Capture Image from Camera</h2>

  <div class="col-md-12">
    <webcam
      [trigger]="invokeObservable"
      (imageCapture)="captureImg($event)"
    ></webcam>
  </div>
  <div class="col-md-12">
    <button class="btn btn-danger" (click)="getSnapshot()">
      Capture Image
    </button>
  </div>
  <div class="col-12">
    <div id="results">Your taken image manifests here...</div>

    <img [src]="webcamImage?.imageAsDataUrl" height="400px" />
  </div>
</div>

Step 5: Incorporate the Webcam Component
Add the following code to src/app/app.component.html:
<app-image-webcam></app-image-webcam>
<router-outlet></router-outlet>

Step 6: Execute your Angular Application
ng ng serve -o

Your Angular application should now have webcam capabilities. This section covers the fundamentals of integrating the ngx-webcam library into an Angular project.
If you run into any problems or have any additional questions, please let me know and I'll be happy to help.
Thank you for reading, and I hope this post has given you a better knowledge of how to use ngx-webcam to capture webcam images in Angular.
"Keep coding, innovating, and pushing the limits of what's possible."

Have fun coding.



Node.js Hosting Europe - HostForLIFE.eu :: How to Choose PDF Library in Node.js?

clock October 13, 2023 09:54 by author Peter

When it comes to document sharing, Adobe's Portable Document Format (PDF) is critical for maintaining the integrity of text-rich and aesthetically pleasing data. Access to online PDF files often necessitates the use of a certain application. Many prominent digital publications now need PDF files. Many companies utilize PDF files to create expert documentation and invoices. Additionally, developers usually employ PDF document generating libraries to meet specific client requirements. The introduction of contemporary libraries has simplified the process of creating PDFs.

What exactly is Node.js?
Node.js is a cross-platform, open-source server environment that works with Windows, Linux, Unix, macOS, and other operating systems. Node.js is a JavaScript back-end runtime environment that uses the V8 JavaScript engine to execute JavaScript code outside of a web browser.

Developers can utilize JavaScript to construct server-side scripts and command-line tools with Node.js. Dynamic web page content is commonly built before a page is sent to a user's web browser by utilizing the server's ability to run JavaScript code. Node.js promotes a "JavaScript everywhere" paradigm that unifies online application development around a single programming language, as opposed to using several languages for server-side and client-side programming.

const PDFDocument = require('pdfkit');
const fs = require('fs');
const doc = new PDFDocument();
doc.text('Hello world', 100, 100)
doc.end();
doc.pipe(fs.createWriteStream('Output.pdf'));

JavaScript
PDFmake

A wrapper library for PDFKit is called pdfmake . The programming paradigm is where there is the most difference:

While pdfmake uses a declarative approach, pdfkit uses the traditional imperative technique. Because of this, concentrating on what you want to perform is simpler than spending time instructing the library on how to get a particular outcome.

But not everything that glitters is gold, and using Webpack and trying to integrate bespoke fonts may cause problems. Unfortunately, there isn't much information regarding this problem available online. If you don't use Webpack, you can still easily clone the git repository and run the script for embedded font.

var fonts = {
  Roboto: {
    normal: 'fonts/Roboto-Regular.ttf',
    bold: 'fonts/Roboto-Medium.ttf',
    italics: 'fonts/Roboto-Italic.ttf',
    bolditalics: 'fonts/Roboto-MediumItalic.ttf'
  }
};

var PdfPrinter = require('pdfmake');
var printer = new PdfPrinter(fonts);
var fs = require('fs');

var docDefinition = {
  // ...
};

var options = {
  // ...
}

var pdfDoc = printer.createPdfKitDocument(docDefinition, options);
pdfDoc.pipe(fs.createWriteStream('output.pdf'));
pdfDoc.end();

JavaScript
jsPDF

Among the PDF libraries on GitHub, jsPDF is a PDF generation library for browsers. It has the most starts, and this is not a coincidence given how reliable and well-maintained it is. Because the modules are exported in accordance with the AMD module standard, using them with nodes and browsers is simple.

For PDFKit, the offered APIs follow an imperative paradigm, making it difficult to create complicated layouts. Including typefaces The only additional step is to convert the fonts to TTF files, which is not difficult. Although jsPDF is not the simplest library to use, the extensive documentation ensures that you won't run into any specific difficulties when using it.

import { jsPDF } from "jspdf";
const doc = new jsPDF();
doc.text("Hello world!", 10, 10);
doc.save("output.pdf");

JavaScript
Puppeteer

Puppeteer is a Node library that offers a high-level API to manage Chrome, as you may know, but it can also be used to as PDF generator. Because the templates must be written in HTML, jsPDF is fairly simple for web developers to use.

Puppeteer has mostly two drawbacks. You must put a backend solution in place. Puppeteer must be launched each time a PDF needs to be created, adding to the burden. It moves slowly.

It might be an excellent solution if the aforementioned drawbacks are not a major issue for you, especially if you need to construct HTML tables and other such things.

const puppeteer = require('puppeteer')

async function printPDF() {
  const browser = await puppeteer.launch({ headless: true });
  const page = await browser.newPage();
  await page.goto('www.google.com', {waitUntil: 'networkidle0'});
  const pdf = await page.pdf({ format: 'A4' });
  await browser.close();
  return pdf
})

JavaScript
PDF-lib

While pdfmake is based on PDFKit, pdf-lib is a library for producing and editing PDFs that is entirely written in Typescript. Even though it was launched after all the other libraries, it has thousands of stars on GitHub, indicating how well-liked it is.

The APIs have a fantastic design and naturally function with both browsers and nodes.It offers many features that other libraries simply don't have, including PDF merging, splitting, and embedding;

Although it is quite powerful, pdf-lib is also very user-friendly. One of the most popular features is the ability to embed font files using Unit8Array and ArrayBuffer, which enables using fs while dealing with nodes and xhr when working in the browser.

When you compare it to other libraries, you'll be able to tell that it performs better, and you can utilize Webpack with it, of course. Additionally, this library uses an imperative approach, which makes it difficult to work with complex layouts.
import { PDFDocument } from 'pdf-lib'

// PDF Create
const pdfDoc = await PDFDocument.create()
const page = pdfDoc.addPage()
page.drawText('Hello World')
const pdfBytes = await pdfDoc.save()

IronPDF
IronPDF for Node.js renders PDFs from HTML strings, files, and web URLs by using the robust Chrome Engine. It is advised to assign this operation to the server side since rendering can be computationally demanding. In order to offload the computational effort and await the outcome, frontend frameworks like ReactJs and Angular can communicate with the server. The outcome can then be shown on the front end side.

Software engineers may produce, modify PDF documents, and extract PDF material with the use of the IronPDF library, which was created and maintained by Iron Software.

When it comes to
    the creation of PDF documents using HTML, URL, JavaScript, CSS, and a variety of image formats
    A signature and headers should be included.
    Add, Copy, Split, Merge, and Delete PDF Pages
    Can able to include CSS properties.
    Performance improvement Async and complete multithreading support

import {PdfDocument} from "@ironsoftware/ironpdf";

(async () => {
  const pdf = await PdfDocument.fromHtml("<h1>Hello World</h1>");
  await pdf.saveAs("Output.pdf");
})();




Node.js Hosting Europe - HostForLIFE.eu :: npm vs yarn vs pnpm

clock September 20, 2023 08:39 by author Peter

Let's look at the differences between npm, yarn, and pnpm in this blog. Package managers such as npm, yarn, and pnpm are extensively used in the JavaScript ecosystem to manage dependencies and packages for Node.js projects. They take different approaches and have distinct features, which can affect how they manage packages and interact with your project.

npm

npm is the default package manager for Node.js and is included with the installation of Node.js. It has a lengthy history and is frequently used in the JavaScript ecosystem. To store and distribute packages, npm makes use of a centralized package registry known as the npm registry. It adds a "node_modules" directory to your project and installs all project dependencies there.

// Install a package
npm install package-name

//Update a package
npm update package-name

// Remove a package
npm uninstall package-name


yarn

// Install a package
yarn add package-name

// update a package
yarn upgrade package-name

// Remove a package
yarn remove package-name


pnpm

pnpm is another package manager for Node.js projects. It aims to solve the issue of disk space usage by using a unique approach. Instead of creating a separate "node_modules" directory for each project, pnpm uses a single global package store and creates symlinks to the required packages in each project's "node_modules" directory. This can significantly reduce the amount of disk space used by your projects.

// Install a package
pnpm add package-name

// update a package
pnpm update package-name

//Remove a package
pnpm remove package-name


HostForLIFE.eu Node.js Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.




AngularJS Hosting Europe - HostForLIFE.eu :: What is Angular Dependency Injection?

clock September 15, 2023 09:16 by author Peter

Dependency Injection (DI) is a core Angular design pattern that aids in the management of dependencies as well as the flow of data and services inside an application. It allows for loose coupling between components, which makes your code more modular, maintainable, and testable.

Why are We using Dependency Injection and without dependency using what problem in real-life example?

Real-Life Example: A Car Factory
Imagine you're managing a car manufacturing factory. In your factory, you have various assembly lines responsible for different parts of the car, such as the engine, chassis, electronics, and tires. Each assembly line relies on specific tools and materials to complete its tasks.

Now, think about how you might manage these dependencies in your car factory.

  • No Dependency Injection (DI): Without dependency injection, each assembly line would have to manage its own dependencies. For example:
    • The engine assembly line would need to procure and maintain its own inventory of engines, tools, and spare parts.
    • The electronics assembly line would need to do the same for electronic components.
    • The tire assembly line would need its own inventory of tires and tire-related equipment.
  • This approach would lead to several problems.
    • Duplication of effort: Each assembly line would have to manage its dependencies separately, resulting in duplicated resources and potential inconsistencies.
    • Maintenance nightmare: If a tool or part needed to be updated or replaced, every assembly line using that tool or part would need to be individually updated.
    • Lack of flexibility: Changing or upgrading components or tools across multiple assembly lines would be challenging and error-prone.
  • Dependency Injection (DI) in the Car Factory: Now, let's introduce dependency injection into the car factory.
    • You create a central inventory management system (akin to Angular's dependency injection container).
    • Each assembly line declares its dependencies on the central system.
    • When an assembly line needs an engine, electronics, or tires, it requests them from the central inventory system (dependency injection).
    • The central system ensures that each assembly line gets the correct parts and tools.
  • Benefits of this approach.
    • Centralized control: You have a single point of control for managing all dependencies, making it easier to update, replace, or upgrade tools and components.
    • Consistency: All assembly lines use the same source for their dependencies, ensuring consistency and reducing errors.
    • Flexibility: You can easily switch out components or tools across the factory by updating the central inventory system.

In Angular
In Angular applications, components, services, and other parts of the application often have dependencies. Dependency injection works similarly to the car factory example:

Angular's DI container manages dependencies and ensures that each component or service gets the correct instances of the dependencies it needs.
This promotes modularity, maintainability, and testability in your Angular application, as you can easily swap out components or services without modifying each dependent part individually.

So, in both the car factory and Angular, dependency injection simplifies management, promotes consistency, and makes it easier to adapt to changes in the dependencies, ultimately leading to more efficient and maintainable systems.

In Angular How to Achieve!
In Angular, dependency injection is achieved through the built-in dependency injection system. Here's how you can achieve dependency injection in Angular.

Step 1. Create Service in your Application
First, you need to create a service that provides the functionality or data you want to inject into other components. Services are classes annotated with the @Injectable decorator. What are the services using this Application? All the functionalities of the service to implemented in the servicefile.

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})

export class EmployeeService {

  EmpApi= environment.EmployeeAPI;
  constructor(private http:HttpClient) { }

  GetEmployeeList(){
    return this.http.get(this.EmpApi+'Employee/List');
  }
}

Step 2. Inject Service into Components
Next, you inject the service into the components or other services where you need it. You can do this by including the service as a parameter in the constructor of the component or service that requires it. Angular's dependency injection system will take care of providing an instance of the service automatically.


import { Component, OnInit } from '@angular/core';
import { EmployeeService } from 'src/app/Service/employee.service';
import { FormBuilder, FormGroup } from '@angular/forms';
import { Router } from '@angular/router';

@Component({

  selector: 'app-employee-list',
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']

})

export class EmployeeListComponent implements OnInit  {

  collectionData: any;
  iframeSrc!: string;
  constructor( private empService:EmployeeService,private route: Router){

  }

  ngOnInit(): void {
   this.empList();
  }

  empList(){
    return this.empService.GetEmployeeList().subscribe((res:any)=>{
      this.collectionData=res.data;

    })
  }
}

Conclusion
That's it! With these steps, you've achieved dependency injection in Angular. The Angular framework will take care of creating and managing the service instances and injecting them where needed, promoting modularity and maintainability in your application.



European Visual Studio Hosting - HostForLIFE :: Boosting Your Productivity with .NET Core CLI Commands

clock September 12, 2023 09:47 by author Peter

In this post, I'll show you how to increase your productivity using.NET Core CLI Commands and how to use.NET Core CLI (Command Line Interface) commands to assist developers speed up their work with a few tips and tricks. We can create, build, add packages, restore packages, run apps, and deploy Core applications using the.Net CLI. I'll go over basic operations like establishing new projects, compiling and running programs, managing dependencies, and working with NuGet packages.

Increasing Productivity with the Command Line Interface in Visual Studio
When we develop a new application in Visual Studio, we use.Net CLI commands internally to create, build, add packages, launch, and deploy apps.

When you install the.NET Core SDK, the.NET Core CLI is also installed by default. As a result, no additional installation is required.CLI for Net Core.
How can I tell if.Net CLI is installed or not?

Open Run and type CMD.

When the command prompt appears, type dotnet and press enter.

CLI Command Syntax: dotnet command> argument> option>
Take note that all commands begin with dotnet. The syntax shown above will assist developers in executing essential instructions from the command-line interface. Let's use the first command (dotnet help) to get help for all commands.

How do I obtain a complete list of all.Net Core commands?


List of all .Net Core commands

Below is a list of all .Net core commands that will appear once we run the "dotnet help" command. Let's list down all commands as below with a short description of what each does.

SDK commands

  • add:  Add a package or reference to a .NET project
  • build: Build a .NET project
  • build-server: Interact with servers started by a build
  • clean: Clean build outputs of a .NET project
  • format: Apply style preferences to a project or solution
  • help: Show command line help
  • list: List project references of a .NET project
  • msbuild: Run Microsoft Build Engine (MSBuild) commands.
  • new: Create a new .NET project or file.
  • NuGet: Provides additional NuGet commands.
  • pack: Create a NuGet package.
  • publish: Publish a .NET project for deployment
  • remove: Remove a package or reference from a .NET project.
  • restore: Restore dependencies specified in a .NET project.
  • run: Build and run a .NET project output.
  • SDK: Manage .NET SDK installation.
  • sln: Modify Visual Studio solution files.
  • store: Store the specified assemblies in the runtime package store.
  • test: Run unit tests using the test runner specified in a .NET project.
  • tool: Install or manage tools that extend the .NET experience.
  • vstest:  Run Microsoft Test Engine (VSTest) commands.
  • workload: Manage optional workloads.

How to create a new console project?
Let's create a new console project using the "dotnet new" Command.
dotnet new console -n MyConsoleAppUsingCLI -o C:\Users\XXXXX\projects\MyConsoleAppUsingCli

Once the above Command runs successfully, We are able to create a console application with the name "MyConsoleAppUsingCli" at the given path "C:\Users\XXXXX\projects\". Let's build the newly created project using the build command.

Build Command: dotnet build C:\Users\peter\projects\MyConsoleAppUsingCli\

Once we run the build command, As per the above screen, the project build succeeded.

How to add a package reference to the new console application?
Let's add a package reference to the new console application using the add package CLI command.



We have added the package "Microsoft.EntityFrameworkCore" to our project. Let's open our console app in Visual Studio and check the newly added package reference in the solution.

As per the above screen, We are able to see Microsoft.EntityFrameworkCore package reference was added successfully.

Run the project using Run CLI Command

Run project using Run CLI Command: dotnet run --project C:\Users\peter\projects\MyConsoleAppUsingCli\MyConsoleAppUsingCli.csproj

In this article, I have demonstrated how to boost productivity with Visual Studio's command-line interface. CLI is very powerful and is used for developing, running, and publishing applications. We have covered essential commands like creating new projects, compiling and running applications, managing dependencies, and handling NuGet packages in console applications. Here I have explained the basic commands required to set up a project and run the new project, but you can explore more on other commands and leverage the power of the.NET Core CLI for streamlined and productive development projects.



Node.js Hosting Europe - HostForLIFE.eu :: Using Immer to Navigate State Management in JavaScript

clock September 6, 2023 09:48 by author Peter

Wrangling application state is a vital skill in the dynamic arena of web development. Keeping code tidy and predictable can be difficult, but the introduction of tools like Immer has provided a breath of fresh air in this sector. Immer has won the hearts of developers all over the world with its ease of use and efficiency in dealing with state changes. This essay will take you on a journey into the world of Immer, looking into its practical implementation, benefits, and how it makes the sometimes difficult chore of state management in JavaScript a lot easier.

Immer, lovingly created by Michel Weststrate, is a library that changes the way we deal with data immutability. It enables us to write code that appears to modify state directly while actually orchestrating the construction of new, immutable state structures.1. Starting Out: InstallationLet's begin your Immer trip by installing the library with npm or yarn.
npm install immer

2. Basic Usage
At the core of Immer is a function called produce. It's the magic wand that takes your current state and a function containing your desired changes and works its enchantment.

import produce from 'immer';

const initialState = { count: 0 };

const nextState = produce(initialState, draftState => {
  draftState.count += 1;
});


3. Taming Nesting
Now comes the pièce de résistance. Immer's prowess shines when dealing with deeply nested objects and arrays. It simplifies complex state structures with ease.
const complexState = {
  user: {
    name: 'Alice',
    address: {
      city: 'Wonderland'
    }
  }
};

const newState = produce(complexState, draftState => {
  draftState.user.name = 'Bob';
  draftState.user.address.city = 'Dreamland';
});


Benefits
    Crystal Clarity: Immer brings lucidity to your code. Instead of fretting about cloning and immutability, you can focus on the changes you wish to make.
    Performance Star: The magic of Immer not only simplifies your code but optimizes performance by reducing memory overhead and avoiding redundant copying.
    Readable Harmony: Code created with Immer mirrors traditional mutable code, fostering understanding and maintainability.

Conclusion

Immer has reimagined the landscape of state management in JavaScript applications. Its knack for handling immutable updates effortlessly, coupled with an approachable syntax, is nothing short of revolutionary. By streamlining the intricate dance of cloning and immutability checks, Immer reduces error risks and transforms the development experience.

In the ever-evolving world of web development, where efficiency and maintainability are paramount, Immer emerges as a steadfast ally. Whether you're working on a modest project or an intricate application, incorporating Immer into your state management arsenal offers cleaner, bug-free code and boosts developer productivity.

So, as you embark on your coding escapades, remember that Immer isn't just a library; it's a compass that guides you through the labyrinth of state management, making your journey more delightful and your code more enchanting.



AngularJS Hosting Europe - HostForLIFE.eu :: View Encapsulation in Angular

clock August 29, 2023 08:16 by author Peter

Angular is a popular and capable framework for developing online apps. View Encapsulation is one of its core characteristics, and it is essential for regulating component styling and behavior. In this article, we'll look into View Encapsulation in Angular, why it's important, and how it works.

What exactly is View Encapsulation?
View Encapsulation is a key notion in Angular that helps to keep styles and behaviors isolated for specific components. It ensures that styles defined in one component do not have an impact on other components in the application. This encapsulation protects your code from unforeseen side effects and encourages modularity and reusability.

View Encapsulation Types
View Encapsulation in Angular comes in three flavors.
Emulated (Default): This is Angular's default behavior. The styles defined in a component's CSS are scoped to that component's view in Emulated View Encapsulation. Angular accomplishes this by adding unique properties to the component's HTML elements. To guarantee that the styles only apply to the component's view, these characteristics are utilized as selectors in the resulting CSS.

/* Component CSS */ .my-component { color: red; }

<!-- Generated HTML -->
<div _ngcontent-c1 class="my-component">Hello, World!</div>

Shadow DOM: Angular uses the browser's native Shadow DOM encapsulation in this mode. Each component is assigned its own Shadow DOM, which separates the component's styling and DOM structure from the rest of the page. This approach offers a high level of encapsulation, but it may be incompatible with outdated browsers.
None: When you select None, Angular does not apply any encapsulation, and the styles defined in a component's CSS file influence the entire application. While this mode is useful in some situations, it should be utilized with caution to avoid unwanted consequences.

How Do I Select the Best Encapsulation Mode?
Choosing the Correct View Encapsulation mode is determined by the requirements and goals of your project:
Emulated: This is the preferred mode for most applications. It strikes a decent compromise between encapsulation and compatibility, and it works effectively in most cases.
Shadow DOM: Use this option if you need a greater level of encapsulation and are developing a modern application for browsers that support Shadow DOM.
None: Use None only when absolutely necessary, such as for global styles that must apply to the entire application. When utilizing this option, be cautious because it can cause style conflicts and maintenance issues.

How Do You Define View Encapsulation?
The View Encapsulation mode for a component can be specified using the encapsulation attribute in the component's metadata. As an example:

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

Conclusion
View Encapsulation is an important feature of Angular that helps maintain clean, modular, and reusable code by segregating component styles and actions. It gives developers the freedom to select the level of encapsulation that best meets the needs of their project. Whether you use Emulated, Shadow DOM, or None, understanding and skillfully employing View Encapsulation will help your Angular applications succeed by fostering clean and maintainable code.

Good luck with your studies :)



AngularJS Hosting Europe - HostForLIFE :: Data Sharing from a Child to a Parent in Angular

clock August 22, 2023 12:06 by author Peter

The @Output decorator is used in this article to share data from child to parent components in Angular. We'll go through the fundamental ideas underlying this technique, show how it works in practice using examples, and explain its benefits in terms of code organization, reusability, and maintainability. By the end of this article, you'll have a solid grasp of how to use the @Output decorator to add efficient data flow methods to your Angular apps.

Understanding Interaction of Components
Components are the building blocks of the user interface in Angular apps. They can be organized hierarchically, with parent components encapsulating child components.

These components frequently need to communicate with one another, transmitting data back and forth. While data sharing between parent and child components is very simple using input attributes, data sharing between child and parent components requires a different technique.

The @Output Decorator is a feature of Angular that allows communication between child and parent components to be more efficient. To emit custom events from the child component, it is used in conjunction with Angular's EventEmitter class. The parent component is aware of these events and can respond appropriately.
Step-by-Step Instructions

Let's go over how to use @Output in Angular to implement data sharing from child to parent components step by step.

Step 1: Make a Child Component

Create the child component first.
ng generate component child

In the child component HTML file (child.component.html), include a button to trigger the data emission.
<button (click)="sendData()">Send Data</button>

In the child component TypeScript file (child.component.ts), import the necessary modules, and create an @Output property and an instance of EventEmitter to emit the data.
import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent {
  @Output() dataEvent = new EventEmitter<string>();

  sendData() {
    this.dataEvent.emit('Hello from child!');
  }
}


Step 2. Use the Child Component in the Parent

Now, use the child component in the parent component HTML file (parent.component.html).
<app-child (dataEvent)="receiveData($event)"></app-child>
<div>{{ receivedData }}</div>


In the parent component TypeScript file (parent.component.ts), define the method to handle the emitted event.
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent {
  receivedData: string = '';

  receiveData(data: string) {
    this.receivedData = data;
  }
}

In conjunction with EventEmitter, Angular's @Output decorator provides a strong mechanism for passing data from child to parent components. You can enable effective communication and interaction between different portions of your program by broadcasting custom events from child components. By fostering a clear separation of concerns, this strategy improves the modularity and maintainability of your system.

This pattern remains a core strategy for component interaction in Angular. Developers may create more dynamic and responsive user interfaces in their Angular applications by mastering the art of exchanging data with @Output.



AngularJS Hosting Europe - HostForLIFE :: Using @Input(), Angular Allows Data to be Shared from Parent to Child Components

clock August 16, 2023 08:08 by author Peter

In this post, we will look at how to use the @Input() decorator in Angular to share data from a parent component to a child component.

Recognizing the @Input() Decorator
The @Input() decorator allows you to transmit data from a parent component to a child component in Angular. It effectively establishes an input property on the child component that may be tied to a value in the template of the parent component. When the value of the input property in the parent component changes, the child component is automatically updated with the new value.

Configuring the Parent Component
Let's begin with a simple example. Consider the following scenario: we have a parent component that displays a user's name, and we wish to pass this name to a child component for display.

Using the Angular CLI, create a new parent component:
ng generate component parent

Open the parent.component.ts file and add the @Input() decorator to the following property:
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  template: `
    <h1>Hello, {{ userName }}!</h1>
    <app-child [inputName]="userName"></app-child>
  `,
})
export class ParentComponent {
  userName = 'Tahir Ansari';
}


Creating the Child Component

Now, let's create the child component that will receive and display the user's name.

Generate a child component using the Angular CLI:
ng generate component child

In the child.component.ts file, use the @Input() decorator to define an input property:
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <p>Received name from parent: {{ receivedName }}</p>
  `,
})
export class ChildComponent {
  @Input() inputName: string;

  get receivedName() {
    return this.inputName;
  }
}


Wiring Up the Module
ensure that you declare both the parent and child components in your module:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';

@NgModule({
  imports: [BrowserModule],
  declarations: [ParentComponent, ChildComponent],
  bootstrap: [ParentComponent],
})
export class AppModule {}


Conclusion
In this article, we've seen how to pass data from a parent component to a child component in Angular using the @Input() decorator. This feature allows for seamless communication between components and enables dynamic updates whenever the data in the parent component changes.

Angular's component-based architecture, combined with features like @Input(), empowers developers to build modular and maintainable applications by promoting the separation of concerns and reusability of components.



AngularJS Hosting Europe - HostForLIFE.eu :: HTTP Interceptors in Angular

clock August 14, 2023 08:28 by author Peter

In this tutorial, we will go through the fundamentals of HTTP Interceptors in Angular and provide some examples using Angular 15.


What exactly is Angular?
Angular is a popular open-source JavaScript web application framework. It was created by Google and is presently maintained by the Google Angular Team. Angular enables developers to create dynamic, single-page applications (SPAs) and offers a disciplined way to developing complicated online apps.

What exactly is an HTTP Interceptor?

HTTP Interceptors are a type of notion in web development and server-side programming that is commonly connected with web frameworks and tools.

These interceptors enable developers to intercept and manage HTTP requests and answers at the application level.

  • They can be used to perform various tasks related to HTTP requests and responses, such as adding headers, handling errors, modifying the request or response data, logging, authentication, etc.
  • HttpInterceptor defines a single method called intercept, which takes two parameters: the HttpRequest and the HttpHandler.

Benefits of HTTP Interceptors
Following are some of the key benefits of using HTTP Interceptors in Angular:
Testability and reusability: Interceptors are easy to test in isolation, allowing you to ensure that each interceptor behaves correctly
Centralized code for cross-cutting concerns: HTTP Interceptors allow you to define logic for common tasks, such as authentication, logging, error handling, or adding headers, in a centralized location.
Global application-level modifications: Interceptors operate globally, intercepting all HTTP requests and responses made by the Angular application. This means you can apply changes or perform actions consistently across multiple API calls without having to modify each individual request or response manually.

Error handling and logging: Interceptors can be utilized to handle errors globally, providing a consistent approach to error reporting and handling throughout the application.

Caching and request/response manipulation: HTTP Interceptors can be leveraged to implement caching mechanisms, reducing redundant requests and optimizing the application’s performance.

Separation of concerns: By using HTTP Interceptors, you can keep concerns related to data fetching and communication (HTTP) separate from the business logic of your components and services.

Security and authentication: Interceptors are commonly used for adding authorization headers or authentication tokens to outgoing requests. This ensures that the user’s authentication status is automatically included in API calls without the need to explicitly set headers in every request.

Easy integration with third-party libraries: Interceptors can be used to integrate with third-party libraries or APIs seamlessly. For example, you can apply a specific format to API responses that are expected by a charting library or a data visualization tool.

Practical Implementation

Let’s start with practical implementation; for that, we need to create a new Angular application using the following command.
ng new angular-http-interceptor-demo

Now, we are going to create different interceptors one-by-one with the help of angular.

1. Logging Interceptor

In Angular, logging interceptors can be used for audit log purposes. If we want to log different incoming and outgoing requests with request and response objects, we can do so with the help of a logging interceptor.

Step 1
Create a new logging interceptor with the help of the following command.
ng g interceptor logging

This command will create the logging interface with a default implementation. So, modify the same as I have shown below.
import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpResponse,
} from '@angular/common/http';
import { Observable, tap } from 'rxjs';

@Injectable()
export class LoggingInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(
    request: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    console.log('Outgoing HTTP request', request);
    return next.handle(request).pipe(
      tap((event: HttpEvent<any>) => {
        console.log('Incoming HTTP response', event);
      })
    );
  }
}


Here, we import the necessary modules and classes from Angular’s HTTP package.

The HttpInterceptor interface allows us to create our custom interceptor, and HttpRequest, HttpHandler, and HttpEvent are classes used for handling HTTP requests and responses.

We also import Observable and Tap from the RxJS library, which is used for handling asynchronous operations.
We call next.handle(request) to pass the request to the next interceptor in the chain or the backend server.
Then, we use the pipe method along with the tap operator to intercept the incoming response.
The tap operator allows us to execute a side effect (in this case, log the response) without modifying the response itself.

Step 2
Provide an interceptor in the app module.
import { LoggingInterceptor  } from './interceptors/logging.interceptor'

 providers: [
    {
      provide: HTTP_INTERCEPTORS, useClass: LoggingInterceptor, multi: true
    }
  ]

In the AppModule, we provide the LoggingInterceptor class as an interceptor using the HTTP_INTERCEPTORS token. The multi: true option ensures that the interceptor is appended to the existing array of interceptors rather than replacing them.

When you make an HTTP request, it will get logged with the following request and response.

In a real-time scenario, you can log this response in a third-party service as per need and requirement.

2. Adding Headers to Requests

In Angular, we can modify HTTP Requests and add some extra value to the request header with the help of an interceptor.

Step 1
Create a new header interceptor with the help of the following command.
ng g interceptor headers

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class HeadersInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    console.log(request)
    const GUID = 'f4179b26-21ac-432c-bcd8-cb4bc6e50981'
    const modifiedRequest = request.clone({
      setHeaders:{
        GUID
      }
    })
    return next.handle(modifiedRequest);
  }
}


Here we first hardcode one GUID that we are going to set inside the header. So, first, we need to clone that HTTP request and use the set headers property to set the value in the request header.

Step 2
Provide an interceptor in the app module.
import { HeadersInterceptor  } from './interceptors/headers.interceptor'

providers: [
    {
      provide: HTTP_INTERCEPTORS, useClass: HeadersInterceptor, multi: true
    }
  ]

In the AppModule, we provide the HeadersInterceptor class as an interceptor using the HTTP_INTERCEPTORS token. The multi: true option ensures that the interceptor is appended to the existing array of interceptors rather than replacing them.

In a real-time scenario, you can use these header values for further processing, like validating requests, and in many other cases.

3. Error Handling Interceptor
In Angular, The Error interceptor is an HTTP interceptor that allows you to handle HTTP errors globally within your application.
When you make HTTP requests to a server, there might be scenarios where the server responds with an error status code, such as 404 or 500.
Handling these errors in each individual HTTP request can be tedious and repetitive.

The Error Interceptor helps you centralize the error-handling logic and provides a consistent way to manage errors across your application.

Step 1
Create a new error interceptor with the help of the following command.
ng g interceptor error

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable, catchError, throwError } from 'rxjs';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        // Handle the error here
        console.error('error occurred:', error);
        //throw error as per requirement
        return throwError(error);
      })
    );
  }
}


Inside the intercept() method, you can use the catchError operator from RxJS to catch any errors that occur during the HTTP request or response handling.
This operator allows you to intercept the error, handle it as needed, and optionally re-throw the error to propagate it further up the observable chain.

Step 2
Provide interceptor in the app module:
import { ErrorInterceptor } from './interceptors/error.interceptor';

  providers: [
    {
      provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true
    }
  ]

In the AppModule, we provide the HeadersInterceptor class as an interceptor using the HTTP_INTERCEPTORS token. The multi: true option ensures that the interceptor is appended to the existing array of interceptors rather than replacing them.

4. Authentication Interceptor
In Angular, an authentication interceptor can be used to add authentication tokens or headers to every outgoing HTTP request. This is helpful when you need to ensure that all API requests are authenticated.

Step 1
Create a new authentication interceptor with the help of the following command.
ng g interceptor auth

import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
} from '@angular/common/http';
import { Observable } from 'rxjs';
//import { AuthService } from './auth.service';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(/*private authService: AuthService*/) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const authToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpheWRlZXAgUGF0aWwiLCJpYXQiOjE1MTYyMzkwMjJ9.yt3EOXf60R62Mef2oFpbFh2ihkP5qZ4fM8bjVnF8YhA";//his.authService.getToken();

    if (authToken) {
      // Clone the request and attach the token
      const authReq = req.clone({
        setHeaders: {
          Authorization: `Bearer ${authToken}`
        }
      });

      return next.handle(authReq);
    }

    // If there is no token, pass the original request
    return next.handle(req);
  }
}


Here we first hardcode one token that we are going to set inside the header. So, for that, first, we need to clone that HTTP request and need to use the set headers property to set the value in the request header.

Step 2
Provide an interceptor in the app module:
import { AuthInterceptor } from './interceptors/auth.interceptor';

  providers: [
    {
      provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true
    }


In the AppModule, we provide the HeadersInterceptor class as an interceptor using the HTTP_INTERCEPTORS token. The multi: true option ensures that the interceptor is appended to the existing array of interceptors rather than replacing them.

When you make an HTTP request, it will set a token inside the header, as shown below.


As you can see, we set one bearer token that you can use for further processing as per requirement.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in