Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE :: Export To Excel In Angular Using ExcelJS

clock May 12, 2023 07:57 by author Peter

This article describes how to export to Excel using excelJS in Angular. In our assignment, I will describe how to export to Excel using excelJS in angular.


What exactly is ExcelJS?

ExcelJS is a well-known JavaScript library that generates Excel spreadsheets in the browser. This section will discuss how to export data from an Angular application to an Excel file using ExcelJS.

For this article, I developed an Angular application. To create an Angular project, the following actions must be taken:

Create Project

Using the following command in the Command Prompt, I created a project.

ng new ExcelJSExample

Open a project in Visual Studio Code using the following commands.
cd ExcelJSExample
Code .


Now in Visual Studio, your project looks as below.

Installation
You need to install the ExcelJS package using npm:
npm install exceljs --save

Also, you need to install the FileSaver.js library, which provides the saveAs() method used to download the Excel file to the user's computer.
npm install file-saver --save

Now create a service file name ExcelService using the following command.
ng g c excelService

You need to import the ExcelJS library in the service file where you want to generate the Excel file.
import * as ExcelJS from 'exceljs';

After installing FileSaver.js, you can import it into the service file as follows
import { saveAs } from 'file-saver';

Then, you need to create a new Excel workbook and worksheet instance.
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('My Sheet');


Next, you need to add the data to the worksheet. You can do this by iterating over the data and adding it to the worksheet using the worksheet.addRow() method
// Add headers
       const headers = Object.keys(data[0]);
       worksheet.addRow(headers);

// Add data
       data.forEach((item) => {
         const row:any = [];
         headers.forEach((header) => {
           row.push(item[header]);
         });
         worksheet.addRow(row);
       });

JavaScript

After adding the data, you can format the worksheet using the ExcelJS API. For example, you can set the column widths using the worksheet.getColumn(colIndex).width property.

worksheet.getColumn(1).width = 15;
worksheet.getColumn(2).width = 20;


Finally, you can save the workbook to an Excel file using the workbook.xlsx.writeBuffer() method.
// Generate Excel file
        workbook.xlsx.writeBuffer().then((buffer: any) => {
          const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          saveAs(blob, `${fileName}.xlsx`);
        });


ExcelService File Code.
import { Injectable } from "@angular/core";
import * as ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';

@Injectable()
export class ExportService{

    exportToExcel(data: any[], fileName: string) {
        const workbook = new ExcelJS.Workbook();
        const worksheet = workbook.addWorksheet('My Sheet');

        // Add headers
        const headers = Object.keys(data[0]);
        worksheet.addRow(headers);

        // Add data
        data.forEach((item) => {
          const row:any = [];
          headers.forEach((header) => {
            row.push(item[header]);
          });
          worksheet.addRow(row);
        });

        worksheet.getColumn(1).width = 15;
        worksheet.getColumn(2).width = 20;


        // Generate Excel file
        workbook.xlsx.writeBuffer().then((buffer: any) => {
          const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
          saveAs(blob, `${fileName}.xlsx`);
        });
      }
}


Here's an example of how you can create a button to trigger the export functionality.

In html file
<button (click)="generateExcel()">Export to Excel</button>

In ts file
generateExcel(){
  const data:any[] = [
    { name: 'John', age: 30 },
    { name: 'Jane', age: 25 },
    { name: 'Bob', age: 40 }
  ];
  this.exportService.exportToExcel(data, 'my-data');
}

With these steps, you should now be able to generate an Excel file with sample data in your Angular project using ExcelJS.

Overall, ExcelJS provides a powerful and flexible API for generating Excel spreadsheets in the browser, and can be easily integrated into Angular applications for exporting data to Excel.



Europe mySQL Hosting - HostForLIFEASP.NET :: How to use IN Operator in MySQL

clock May 11, 2023 08:16 by author Peter

When filtering data based on a particular set of values, MySQL's IN operator is a potent tool. You may use it to supply a list of values to check if a column's value is present in that list. This article will examine the syntax and application of MySQL's IN operator and offer examples of its use in various contexts.

What is IN operator in MySQL?
In MySQL, the IN operator enables you to provide several values in a WHERE clause, which is shorter than using multiple OR conditions. In your database queries, you can quickly and simply specify a set of values to match against a specific column by using IN.

Syntax
SELECT columnName(s)
FROM tableName
WHERE columnName IN (value1, value2, ...);

OR
SELECT columnName(s)
FROM tableName
WHERE columnName IN (SELECT STATEMENT);

Create a table named StudentData.
CREATE TABLE StudentData (
stuDataId INT AUTO_INCREMENT,
stuId INT NOT NULL,
studentName VARCHAR(50) NOT NULL,
Address VARCHAR(50) NOT NULL,
City VARCHAR(50) NOT NULL,
Country VARCHAR(50) NOt NULL,
PRIMARY KEY(stuDataId)
);


Now, examining the StudentData table
select * from StudentData;

Using IN operator with a list of values in MySQL

In MySQL, you may define a list of values to search for in a column by using the IN operator. Instead of creating separate OR conditions for each value, you can use this to search for many values at once.

Example
SELECT * FROM StudentData
WHERE City IN ('
London', 'UK');

IN in MySQL
Example shows how to filter data from MySQL's "StudentData" table using the IN operator. In this instance, the query is choosing all rows where either "Noida" or "Delhi" is the value of the "City" column.
Using the NOT IN operator with a list of values in MySQL

The NOT IN operator in MySQL is used to exclude results that match a list of given values. When you wish to exclude particular values from the results of your query, this is helpful.

Example
SELECT * FROM StudentData
WHERE City NOT IN (
'London', 'UK');

IN in MySQL
The SQL query shown above makes use of MySQL's NOT IN operator. It chooses every row from the "StudentData" table that has neither "Noida" nor "Delhi" in the "City" column.
Using IN operator with a subquery in MySQL

To compare data returned by a subquery to a column in a table, the IN operator can also be used with a subquery. Parentheses surround the subquery, which is then put within the IN operator.

Example
SELECT * FROM StudentData
WHERE City IN (SELECT City FROM OtherStudentData WHERE Enrolled = 'Yes');


In this example, the subquery (SELECT City FROM OtherStudentData WHERE Enrolled = 'Yes') returns a list of all cities where students are enrolled in some other data table. This list of cities is then used in the WHERE clause with the IN operator to select all records from StudentData where the city matches any of the cities returned by the subquery.

Performance Considerations of IN Operator in MySQL
When using the IN operator in MySQL, there are some performance considerations to remember. Using IN with a large list of values can slow down the query, especially if the list is not indexed.

To optimize queries that use IN, you can consider the following strategies:
Use indexes: Indexes can greatly improve the performance of queries that use IN. Make sure to create indexes on the columns used in the IN condition.
Use EXISTS: In some cases, using EXISTS instead of IN can be more efficient. EXISTS returns true if a subquery returns at least one row, whereas IN returns true if a value matches any value in a list. EXISTS can be faster than IN because it stops evaluating the subquery when it finds a match.
Use JOINs: Another way to optimize queries that use IN is to use JOINs instead. This can be especially useful if the list of values is obtained from another table.
Limit the list of values: If possible, limit the list of values used in the IN condition. This can be done by adding additional conditions to the WHERE clause or by filtering the data before it is passed to the query.

Using these strategies, you can optimize your queries and improve the performance of your MySQL database.

To sum it up, the IN operator in MySQL is a strong tool that lets you select query results based on a set of values or a subquery. However, it's important to take into account any possible effects on query speed, especially when working with huge datasets. You may make effective and efficient use of the IN operator by following best practises.

Thanks for reading this article. I hope this helped you to grasp the topic of Use In in MySQL.

FAQs

Q. What is the difference between IN and EXISTS in MySQL?

A. The IN operator matches a column value to a list of possible values, while the EXISTS operator checks if a subquery returns any rows. IN is used to filter data based on a set of possible values, while EXISTS is used to check if data exists in another table.

Q. Can I use IN with a subquery in MySQL?
A. Yes, you can use IN with a subquery in MySQL. The subquery must return a set of values that can be matched with the column being filtered.

Q. How can I optimize queries that use the IN operator in MySQL?
A. One way to optimize queries that use IN is to ensure that the column being filtered is indexed. This can significantly improve query performance. Another strategy is to use EXISTS instead of IN if possible, as EXISTS may perform better in some cases. Additionally, it's important to use the most specific data type possible for the values being compared, as this can also improve performance.



AngularJS Hosting Europe - HostForLIFE :: Angular Reactive Form

clock May 8, 2023 10:43 by author Peter

Angular Forms is a powerful feature of the Angular framework that allows you to create complex forms that handle user input and perform validations. There are two types of forms in Angular: Template-driven forms and Reactive forms. In this answer, I will describe Reactive forms with an example.

Reactive Forms  
Reactive forms use a model-driven approach to handle form inputs. You create a form model in your component that maps to the form controls in your template. This gives you more control over the form and allows you to create dynamic forms that can change based on user input.

Here is an example of how to create a Reactive form in Angular.

First, you need to import the necessary modules into your component.
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'app-example',
  template: `
    <form [formGroup]="myForm" (ngSubmit)="onSubmit()">
      <label>
        Name:
        <input type="text" formControlName="name">
      </label>
      <label>
        Email:
        <input type="email" formControlName="email">
      </label>
      <button type="submit">Submit</button>
    </form>
  `,
})
export class ExampleComponent {
  myForm: FormGroup;

  constructor() {
    this.myForm = new FormGroup({
      name: new FormControl('', Validators.required),
      email: new FormControl('', [Validators.required, Validators.email]),
    });
  }

  onSubmit() {
    console.log(this.myForm.value);
    // Do something with the form data
  }
}


In this example, we created a Reactive form with two form controls: name and email. The form model is defined in the ExampleComponent class using the FormGroup and FormControl classes. The Validators class defines the validation rules for each form control.

And must include FormsModule and ReactiveFormsModule in your Module.

In the template, we bind the form model to the formGroup directive and each form control to the formControlName directive.

When the user submits the form, the onSubmit method is called. You can access the form data using the value property of the form model.

Conclusion
Reactive forms give you more control over your form and allow you to create complex forms with dynamic validation rules. While they require more code to set up, they are more powerful and flexible than Template-driven forms.

Thanks For Reading.



AngularJS Hosting Europe - HostForLIFE :: What Are Angular Portals and How Do You Use Them?

clock May 4, 2023 09:48 by author Peter

If you've used Angular, you've probably run into the problem of rendering content in a situation other than the one in which it was defined. For instance, you might not want to include the dialog markup in the main component's design but still want to display a dialog or popover that covers a portion of the page. In the past, this needed laborious and error-prone workarounds, but now that Angular gateways are available, it's simpler than ever.


You can render a portion of your application in a different location in the DOM tree than where it is defined using Angular portals, also referred to as portal components. When you need to display content in a new context, this can help you design more adaptable and reusable components.

In this post, we'll define Angular portals, describe how they operate, and give usage examples.

An Angular portal can render content in a location other than the one where it was defined, in theory. To do this, a portal component that acts as a placeholder for the content must be created, and it must then be attached to the desired spot in the DOM tree using a portal outlet.

The portal component defines the syntax and behavior of the content you want to render and is a typical Angular component. The main distinction is that the portal component offers a place where the content will be added rather than rendering the material directly. The ng-content directive is used to define this slot.

A directive known as the portal outlet specifies where the portal will be presented. An Angular component or DOM element can serve as the outlet. One of the main advantages of using a portal outlet is that you can render the content in a different place in the DOM tree than where the portal component was declared. This can be helpful in situations where UI elements such as tooltips, modals, and others need to be rendered in a different context than where they were created.

How Do Angular Portals Work?
You must adhere to a few steps in order to use Angular portals,

Define the portal component in Step 1
The portal component that will act as a placeholder for the material you wish to render must first be created. Although it shouldn't render the content itself, this component should specify the markup and behavior of the content. Instead, it ought to have a space where the content can be added.

Here is an illustration of a straightforward message-display portal component.

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

@Component({
  selector: 'app-message-portal',
  template: `
    <div class="message">
      <ng-content></ng-content>
    </div>
  `,
})
export class MessagePortalComponent {}

The MessagePortalComponent uses the ng-content directive in this example to define a slot for the content. The content will be rendered inside this slot when the portal is connected to a portal output.


Step 2: Construct the Portal

The following step is to create an instance of the portal component that will be rendered. Typically, this is done in the component that will host the portal.


The ComponentPortal class from the @angular/cdk/portal package can be used to generate the portal instance. The portal component type is passed as an input to this class.


The following is an example of how to build a portal instance.

import { ComponentPortal } from '@angular/cdk/portal';
import { MessagePortalComponent } from './message-portal.component';

export class MyComponent {
  private portal = new ComponentPortal(MessagePortalComponent);
}


In this example, the MyComponent component creates a MessagePortalComponent portal instance.

Step 3: Connect the Portal to the Portal Outlet

Once you've created a portal instance, you must connect it to a portal outlet in the desired DOM tree location. This may be accomplished by utilizing the PortalOutlet class from the @angular/cdk/portal package.

 

Here's an illustration of how to make a gateway outlet.

import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { CdkPortalOutlet } from '@angular/cdk/portal';

@Component({
  selector: 'app-my-component',
  template: `
    <div>
      <h1>Welcome to my app</h1>
      <ng-container #portalOutlet></ng-container>
    </div>
  `,
})
export class MyComponent implements AfterViewInit {
  @ViewChild(CdkPortalOutlet)
  portalOutlet: CdkPortalOutlet;

  ngAfterViewInit() {
    this.portalOutlet.attach(this.portal);
  }
}

In this example, the CdkPortalOutlet directive is used by the MyComponent component to specify a portal outlet. This directive produces a placeholder for the portal's rendering.

The portal is associated with the portal output using the attach method in the ngAfterViewInit lifecycle hook. This method accepts as an argument the gateway instance established in step 2.

Step 4: Utilize the Portal
Finally, you can use the portal by populating it with content. This is accomplished by including the content to be rendered within the portal component tags.

Here's an example of how to show a message using the gateway.
<app-my-component>
  <app-message-portal>
    Hello, world!
  </app-message-portal>
</app-my-component>


In this example, the app-my-component component hosts the portal, and the material to be rendered is contained within the app-message-portal tags.

Advantages of Using Angular Portals
Using Angular portals has various advantages.
Separation of concerns: You may isolate the markup and behavior of the content from the area where it will be rendered by building a portal component that provides a slot for the content.

Portals can be utilized in numerous situations, allowing you to create more flexible and reusable components.

Improved performance: Portals leverage the Angular Change Detection system to efficiently update content when it changes, resulting in better performance when compared to other approaches.

Improved accessibility- By incorporating a portal component that defines the semantics and accessibility of the material, you can ensure that the rendered content is accessible and adheres to best practices.

Use of Angular Portals Examples
Here are some examples of how Angular portals can be used in your applications:
Modals- Use a portal to display a modal dialog that overlays a portion of the page.
Tooltips- Use a portal to display a tooltip when the user hovers over an element.
Popovers- Render a popover that displays additional information when the user clicks on an element using a portal.


Use a gateway to render form fields based on user input or other conditions.

This article has discussed what Angular portals are, how they work, and provided examples of how to use them. You may increase the efficiency and accessibility of your applications by leveraging portals to create more flexible and reusable components. With these advantages, it's evident that Angular portals are a valuable tool that every Angular developer should have in their toolbox.



European Visual Studio 2022 Hosting - HostForLIFE :: Create Your First Visual Studio Extension

clock April 19, 2023 08:09 by author Peter

In this article, we will look into the basics of visual studio extension. Also, create one application and understand file structure and implementation.


How to Create a New VSIX Project?
Step 1
Install Visual Studio extension development from Tools-> Get Tools and Features.

Step 2
Next, install Extensibility Essentials 2022, which helps us write different extensions.

Step 4
Configure a new project.


Step 3
Create a new VSIX Project

  • Many VSIX project templates are available, each with its purpose and usage.
  • VSIX Project w/Command (Community) template comes with a command hooked up, which helps us start a new extension easily after creating commands and configuring the same with Visual Studio.
  • VSIX Project w/Tool Window (Community) template with tool window command.
  • Empty VSIX Project (Community) and VSIX Project (Community) templates for MEF-only extensions or use in advanced customized scenarios.

But, here in this article, we will use VSIX Project w/Command (Community) template.

Step 5
Default Project Structure

As you can see, it will create different files inside the VSIX project solution, each with its purpose. So, we looked into them one by one and understood their purpose of it.

MyCommand.cs
The command handler file executes logic when the user triggers the command.
namespace VSIXProject
{
    [Command(PackageIds.MyCommand)]
    internal sealed class MyCommand : BaseCommand<MyCommand>
    {
        protected override async Task ExecuteAsync(OleMenuCmdEventArgs e)
        {
            await VS.MessageBox.ShowWarningAsync("VSIXProject", "Button clicked");
        }
    }
}

Resources/icon.png
This file is used to set icons for our extension. We can also set our custom icons for the same.

source.extension.vsixmanifest
It contains metadata of our extensions project like name, description, version, tags, author, etc.
// ------------------------------------------------------------------------------
// <auto-generated>
//     This file was generated by the extension VSIX Synchronizer
// </auto-generated>
// ------------------------------------------------------------------------------
namespace VSIXProject
{
    internal sealed partial class Vsix
    {
        public const string Id = "VSIXProject.34901e8a-0458-4252-9662-9ca734552faf";
        public const string Name = "VSIXProject";
        public const string Description = @"Empty VSIX Project.";
        public const string Language = "en-US";
        public const string Version = "1.0";
        public const string Author = "jaydeepvpatil225";
        public const string Tags = "";
    }
}

VSCommandTable.vsct
This XML file contains the binding of different commands with ids, button text for our command, parent menu, and many more.
<?xml version="1.0" encoding="utf-8"?>
<CommandTable xmlns="http://schemas.microsoft.com/VisualStudio/2005-10-18/CommandTable" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <Extern href="stdidcmd.h"/>
  <Extern href="vsshlids.h"/>
  <Include href="KnownImageIds.vsct"/>
  <Include href="VSGlobals.vsct"/>

  <Commands package="VSIXProject">
    <Groups>
      <Group guid="VSIXProject" id="MyMenuGroup" priority="0x0600">
        <Parent guid="VSMainMenu" id="Tools"/>
      </Group>
    </Groups>

    <!--This section defines the elements the user can interact with, like a menu command or a button
        or combo box in a toolbar. -->
    <Buttons>
      <Button guid="VSIXProject" id="MyCommand" priority="0x0100" type="Button">
        <Parent guid="VSIXProject" id="MyMenuGroup" />
        <Icon guid="ImageCatalogGuid" id="StatusInformation" />
        <CommandFlag>IconIsMoniker</CommandFlag>
        <Strings>
          <ButtonText>My Command</ButtonText>
          <LocCanonicalName>.VSIXProject.MyCommand</LocCanonicalName>
        </Strings>
      </Button>
    </Buttons>
  </Commands>

  <Symbols>
    <GuidSymbol name="VSIXProject" value="{bb2edf02-da6e-4673-b2a4-b3b7449b2ce7}">
      <IDSymbol name="MyMenuGroup" value="0x0001" />
      <IDSymbol name="MyCommand" value="0x0100" />
    </GuidSymbol>
  </Symbols>
</CommandTable>

VSIXProjectPackage
This file has one Initialize method that registers commands asynchronously when we run our extension project.
global using Community.VisualStudio.Toolkit;
global using Microsoft.VisualStudio.Shell;
global using System;
global using Task = System.Threading.Tasks.Task;
using System.Runtime.InteropServices;
using System.Threading;

namespace VSIXProject
{
    [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
    [InstalledProductRegistration(Vsix.Name, Vsix.Description, Vsix.Version)]
    [ProvideMenuResource("Menus.ctmenu", 1)]
    [Guid(PackageGuids.VSIXProjectString)]
    public sealed class VSIXProjectPackage : ToolkitPackage
    {
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
        {
            await this.RegisterCommandsAsync();
        }
    }
}


Step 6

Run Project
When we run the project, it will open one experimental visual studio and keep its own things separately related to settings.

As we can see, our command comes up under the Tool menu “MyCommand”, and when you click on it, a message popup with details that we put inside the MyCommand file. Here we just looked into the basics, but you can customize it as required and perform different operations.

This is all about VSIX Sample Project. Here we discussed the basics of VSIX Extension with a demo application implementation and its file structure details.
Happy Coding!!!



AngularJS Hosting Europe - HostForLIFE :: How To Set And Get Cookies In Angular With Example?

clock April 14, 2023 10:22 by author Peter

You can use the next-cookie-service package to set and get cookies in Angular. Here's an example,


1. First, install the ngx-cookie-service package using the following command.
npm install ngx-cookie-service --save

2. Import the CookieService from the ngx-cookie-service package in your component.
import { CookieService } from 'ngx-cookie-service';

3. Create an instance of the CookieService in your constructor.
constructor(private cookieService: CookieService) { }

4. To set a cookie, use the set method of the CookieService.
this.cookieService.set('cookieName', 'cookieValue');

5. To get a cookie, use the get method of the CookieService.
const cookieValue = this.cookieService.get('cookieName');

Here's the complete code for setting and getting a cookie:
import { Component } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private cookieService: CookieService) {
    // Set cookie
    this.cookieService.set('cookieName', 'cookieValue');

    // Get cookie
    const cookieValue = this.cookieService.get('cookieName');
    console.log('Cookie value:', cookieValue);
  }
}


Note. Remember to import the CookieModule in your app.module.ts file after installing the package.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CookieModule } from 'ngx-cookie';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    CookieModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


I hope this helps. If this helps you, then share it with others.
Sharing is caring! :)



AngularJS Hosting Europe - HostForLIFE :: Interceptors In Angular Along With Benefits

clock April 10, 2023 08:33 by author Peter

In Angular, an interceptor is a middleware that intercepts HTTP requests and responses. Interceptors are used to manipulate or transform HTTP requests and responses globally. This means you can modify HTTP requests and responses in one place and affect all the requests and responses that go through that place.

 

Ininterceptors In Angular
Interceptors are a powerful tool in Angular as they can be used for a wide variety of tasks, such as,
    Adding authorization headers to requests
    Logging requests and responses
    Adding or removing parameters from requests
    Transforming response data

How to implement an interceptor in Angular?
To implement an interceptor in Angular, you need to create a class that implements the HttpInterceptor interface. The HttpInterceptor interface has two methods to implement: intercept() and, optionally, handleError().

So let's start. Here's an example of an interceptor that adds an authorization header to every HTTP request,
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {
        // Get the access token from your authentication service
        const accessToken = this.authService.getAccessToken();
        // Clone the request and add the authorization header
        const authRequest = request.clone({
            headers: request.headers.set('Authorization', `Bearer ${accessToken}`)
        });
        // Pass the cloned request to the next handler in the chain
        return next.handle(authRequest);
    }
}


In this example, the AuthInterceptor class implements the HttpInterceptor interface and overrides the intercept() method. In the intercept() method, we get the access token from our authentication service and clone the incoming request, adding an authorization header. We then pass the cloned request to the next handler in the chain using the next.handle() method.

To use this interceptor, register it with the Angular HTTP client. You can do this by providing it in the provider's array of your AppModule,
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AuthInterceptor } from './auth.interceptor';

@NgModule({
    imports: [BrowserModule, HttpClientModule],
    providers: [{
        provide: HTTP_INTERCEPTORS,
        useClass: AuthInterceptor,
        multi: true
    }]
})
export class AppModule {}


In this example, we import the HttpClientModule and our AuthInterceptor class. We then provide our interceptor in the provider's array using the HTTP_INTERCEPTORS token. The multi-option is set to true, which means that this interceptor is added to the existing array of HTTP interceptors rather than replacing it.
Benefits of using interceptors in Angular

    Interceptors allow the manipulation of HTTP requests and responses globally, making it easy to implement cross-cutting concerns such as authentication and error handling.
    Interceptors can reduce code duplication by providing a centralized place to modify requests and responses.
    Interceptors can be easily added or removed, making it easy to change the behavior of your application without having to modify every HTTP request and response.

Summary
Interceptors are a powerful Angular tool that allows you to manipulate HTTP requests and responses globally. They can be used for various tasks and provide a centralized place to modify requests and responses. By using interceptors, you can reduce code duplication and easily add or remove functionality from your application.



AngularJS Hosting Europe - HostForLIFE :: Build Multi-Repo Micro-Frontend Using Angular And Webpack 5 Module Federation

clock April 3, 2023 07:47 by author Peter

Angular is one of the popular Single Page Application framework. It is commonly used to build monolithic front-end applications. It supports the lazy loading of modules, allowing the browser to load the feature modules on demand. Angular internally uses Webpack as the bundling tool. Micro-frontend is a pattern that allows you to build the frontend applications as individual applications(remote) that can be integrated within a shell(host) application. Module federation plugin of the Webpack allows you to load these micro-frontend applications into a shell application.


This tutorial helps you to build Micro-frontends using Angular and Webpack Module Federation.
Prerequisites
    Angular CLI: Version 14.0.0 (use exact version)
    Module Federation library for Angular (@angular-architects/module-federation): 14.3.0 (compatible to Angular 14.0.0)
    Node 16.x or later
    Visual Studio Code

Build first remote(Micro-frontend) application (Auth-MFE)

1) Open the command terminal and create an Angular workspace for the first micro-frontend application. Run the following command to create a workspace for auth-app-remote.
ng new auth-app-remote --create-application false --skip-tests

2) Switch to the workspace folder and create a project inside the auth-app-remote.
cd auth-app-remote
ng g app auth-mfe --skip-tests --routing

3) Add a home component to the application.
ng g c components/home --project auth-mfe

4) Create a feature module for the auth-mfe project.
ng g module --project auth-mfe --routing auth

5) Add a component login to the auth feature module.
ng g c --project auth-mfe --module auth auth/components/login

6) Updates the auth-routing.module.ts file with the following route configuration.
const routes: Routes = [{
    path: 'login',
    component: LoginComponent
}];
@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class AuthRoutingModule {}


7) Update the app-routing.module.ts file with the following routing configuration.
const routes: Routes = [{
    path: '',
    component: HomeComponent,
    pathMatch: 'full'
}, {
    path: 'auth',
    loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule)
}];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {}

8) Install the bootstrap and jquery libraries to the project.
npm install [email protected] jquery --save

9) Open the app.component.html file and replace the existing code with the following code.
<nav class="navbar navbar-expand-lg bg-primary bg-body-tertiary" data-bs-theme="dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Auth MFE</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" routerLink="auth/login">Login</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <router-outlet></router-outlet>
</div>


10) Run and test the application.
ng serve --port 4200 -o

Configure the application with module federation
11) Install the Module federation plugin to the application. Install the supported version of the @angular-architects/module-federation based on the Angular CLI. In this demo, we are using Angular 14.0.0, so the supported version of the module federation plugin is 14.3.0.
ng add @angular-architects/[email protected] --type remote --project auth-mfe --port 4200

12) Open the webpack.config.js file, and update the name and exposes properties.
const {
    shareAll,
    withModuleFederationPlugin
} = require('@angular-architects/module-federation/webpack');
module.exports = withModuleFederationPlugin({
    name: 'auth-mfe',
    exposes: {
        './Module': './projects/auth-mfe/src/app/auth/auth.module.ts',
    },
    shared: {
        ...shareAll({
            singleton: true,
            strictVersion: true,
            requiredVersion: 'auto'
        }),
    },
});


13) Run and test the application.
ng serve --port 4200 -o

Build second remote(Micro-frontend) application (Book-MFE)

1) Open the command terminal and create an Angular workspace for another micro-frontend application. Run the following command to create a workspace for book-app-remote
ng new book-app-remote --create-application false --skip-tests

2) Switch to the workspace folder and create a project inside the book-app-remote.
cd book-app-remote
ng g app book-mfe --skip-tests --routing


3) Add a home component to the application.
ng g c components/home --project book-mfe

4) Create a feature module for the book-mfe project.
ng g module --project book-mfe --routing book

5) Add a component book-list to the book feature module.
ng g c --project book-mfe --module book book/components/book-list

6) Updates the book-routing.module.ts file with the following route configuration.
const routes: Routes = [{
    path: 'list',
    component: BookListComponent
}];
@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class BookRoutingModule {}

7) Update the app-routing.module.ts file with the following routing configuration.
const routes: Routes = [{
    path: '',
    component: HomeComponent,
    pathMatch: 'full'
}, {
    path: 'books',
    loadChildren: () => import('./book/book.module').then(m => m.BookModule)
}];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {}

8) Install the bootstrap and jquery libraries to the project.
npm install [email protected] jquery --save

9) Open the app.component.html file and replace the existing code with the following code.
<nav class="navbar navbar-expand-lg bg-primary bg-body-tertiary" data-bs-theme="dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Book MFE</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" routerLink="books/list">Books</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <router-outlet></router-outlet>
</div>


10) Run and test the application.
ng serve --port 4200 -o

Configure the application with module federation
11) Install the Module federation plugin to the application.
ng add @angular-architects/[email protected] --type remote --project book-mfe --port 4300

12) Open the webpack.config.js file, and update the name and exposes properties.
const {
    shareAll,
    withModuleFederationPlugin
} = require('@angular-architects/module-federation/webpack');
module.exports = withModuleFederationPlugin({
    name: 'book-mfe',
    exposes: {
        './Module': './projects/book-mfe/src/app/book/book.module.ts',
    },
    shared: {
        ...shareAll({
            singleton: true,
            strictVersion: true,
            requiredVersion: 'auto'
        }),
    },
});


13) Run and test the application.
ng serve --port 4300 -o

Create a Shell(Host) Application (BookStore-Host)
1) Open the command terminal and create an Angular workspace for a shell application. Run the following command to create a workspace for bookstore-host .
ng new bookstore-host --create-application false --skip-tests

2) Switch to the workspace folder and create a project inside the bookstore-host.
cd bookstore-host
ng g app bookstore-shell --skip-tests --routing


3) Add a home component to the application.
ng g c components/home --project bookstore-shell

4) Update the app-routing.module.ts file with the following routing configuration.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';

const routes: Routes = [{
    path: '',
    component: HomeComponent,
    pathMatch: 'full'
}];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {}


5) Install the bootstrap and jquery libraries to the project.
npm install [email protected] jquery --save

6) Open the app.component.html file and replace the existing code with the following code.
<nav class="navbar navbar-expand-lg bg-primary bg-body-tertiary" data-bs-theme="dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Bookstore</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" routerLink="">Home</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <router-outlet></router-outlet>
</div>

7) Run and test the application.
ng serve --port 5000 -o

Configure the shell application with module federation

8) Install the Module federation plugin to the application.
ng add @angular-architects/[email protected] --type host --project bookstore-shell --port 5000

9) Open the webpack.config.js file, and update the remote property.
const {
    shareAll,
    withModuleFederationPlugin
} = require('@angular-architects/module-federation/webpack');
module.exports = withModuleFederationPlugin({
    remotes: {
        "auth-mfe": "http://localhost:4200/remoteEntry.js",
        "book-mfe": "http://localhost:4300/remoteEntry.js"
    },
    shared: {
        ...shareAll({
            singleton: true,
            strictVersion: true,
            requiredVersion: 'auto'
        }),
    },
});


10) Open the app-routing.module.ts file and update the routes for loading the auth and book micro-frontends.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';

const routes: Routes = [{
    path: '',
    component: HomeComponent,
    pathMatch: 'full'
}, {
    path: 'auth',
    loadChildren: () => import('auth-mfe/Module').then(m => m.AuthModule)
}, {
    path: 'books',
    loadChildren: () => import('book-mfe/Module').then(m => m.BookModule)
}];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {}


11) Update the app.component.html to add the hyperlinks for invoking book list and login components from the micro-frontends.
<nav class="navbar navbar-expand-lg bg-primary bg-body-tertiary" data-bs-theme="dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Bookstore</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" routerLink="">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" routerLink="books/list">Books</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" routerLink="auth/login">Login</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <router-outlet></router-outlet>
</div>

12) Run and test the application.
ng serve --port 5000 -o



AngularJS Hosting Europe - HostForLIFE :: What Is Interceptor In Angular And Use Cases Of Interceptor?

clock March 31, 2023 07:36 by author Peter

In Angular, an interceptor is a middleware service that can intercept HTTP requests and responses from the application to the server. The interceptor can modify the requests or responses, add headers or tokens, handle errors, or perform any other necessary actions.


Interceptors are defined as services in Angular, and they can be added to the application by providing them in the HTTP_INTERCEPTORS multi-provider token.

Here's an example of an interceptor that adds an authorization token to every outgoing HTTP request:
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 token = localStorage.getItem('auth_token');
    if (token) {
      const authRequest = request.clone({
        headers: request.headers.set('Authorization', `Bearer ${token}`)
      });
      return next.handle(authRequest);
    }
    return next.handle(request);
  }
}


In this example, the AuthInterceptor class implements the HttpInterceptor interface and provides the intercept() method. The intercept() method receives the incoming request and the HttpHandler object that allows us to pass the request to the next interceptor or the final HTTP handler.

The method first checks if an authorization token is present in the local storage. If the token is present, the method creates a new request with an additional Authorization header that includes the token. If the token is absent, the method passes the original request to the next handler.

To use this interceptor in your application, you need to provide it in the HTTP_INTERCEPTORS multi-provider token. Here's an example of how to do this:
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth.interceptor';

@NgModule({
  imports: [HttpClientModule],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
  ]
})
export class AppModule { }


In this example, the AuthInterceptor is provided in the HTTP_INTERCEPTORS token as a multi-provider, which means that it can be combined with other interceptors if needed.

Interceptors in Angular have several use cases:

  • Authentication and authorization: You can use an interceptor to add authentication tokens or authorization headers to outgoing requests. This helps ensure that only authorized users can access protected resources.
  • Error handling: You can use an interceptor to handle errors that occur during HTTP requests. This can be useful for handling network, timeouts, or server-side errors.
  • Caching: You can use an interceptor to cache responses from the server, which can improve the performance of your application.
  • Logging: You can use an interceptor to log HTTP requests and responses. This can be useful for debugging and monitoring your application's performance.
  • Transformation of requests and responses: You can use an interceptor to modify the request or response data. This can be useful for adding or removing data or transforming data to match the format your application expects.

Overall, interceptors are a powerful feature of Angular that can help you improve your application's performance, security, and reliability. By using interceptors, you can centralize common functionality that needs to be applied to all HTTP requests and keep your code clean and modular.

Interceptors were introduced in Angular version 4.3.0 and are available in all subsequent versions. So, if you use Angular 4.3.0 or later, you can take advantage of the interceptor feature.

Note that interceptors are part of the @angular/common/http module, so you must import this module into your application to use interceptors. If you are using an earlier version of Angular that does not support interceptors, you can consider upgrading your application to a newer version of Angular to take advantage of this feature.

I hope this helps. If this helps you, then share it with others.

Sharing is caring! :)



AngularJS Hosting Europe - HostForLIFE :: Angular 15 – What’s New and Why to Upgrade?

clock March 27, 2023 08:16 by author Peter

As we know, Google has released a new version of Angular i.e. Angular 15 recently. As per the expectation, the Angular team majorly focussed on the stability and performance improvement of the framework. So, in this article, we will discuss the new features introduced in Angular 15 and also discuss how to upgrade any existing applications to Angular 15.  Angular 15 is released on November 16, 2022. As we already mentioned, this version mainly contains many features related to the performance and stability of the application.

What is New in Angular 15?
The Client-Side Web-based application development process changed a lot once the Angular team introduced the new versions of Angular a few years back. All the current versions of Angular are based on TypeScript languages and are open-source-based frameworks. As developers, we can use develop any client-based SPA or Single-Page Application very easily with the help of Angular. On November 2022, Google released the new version of the Angular framework, i.e. Angular 15. Angular 15 is released with many stable standalone API supports which helps developers to bootstrap any web application by using a single component. As we know, the previous version Angular 14 is the most feature-based release by the Angular team and it also supports the latest TypeScript version i.e. TypeScript 4.7. As per the earlier release, the Angular team also declared that by removal of Angular’s Legacy Compiler and the rendering pipeline in the past releases, improves the performance of the application along with the developer’s experience.

Some of the key functionalities and features included in the Angular 15 are as follows –
    Standalone Stable APIs
    Directive Composition API
    Improve Stack Traces for Debugging
    Http with provideHttpClient
    Stable Image Directives
    Dependency Injection
    Functional Route Guards
    Automatic Imports in Language Service
    Angular CLI improvements
    CDK Based Listbox

With the latest release of Angular 15, we can use the single component concepts in Router, Angular Element, HttpClient, and other areas. So, if we use the Standalone Component, then it makes the development process much easier and also can provide us with an alternative way of using ngModule. So, the developer can develop any application without the ngModules which reduces the unnecessary complex design of any application.

Different Characteristics of Angular 15
So, while we discuss the Angular 15-related new characteristics or features, we should understand the changes done in Angular 15 compared to the previous versions of Angular Framework. Through this article, our primary focus is to discuss related the key features or characterize of the Angular frameworks. So, as a Framework, Angular 15 has many more features than those mentioned in this article. But, here, we only focus on some key or important features related to Angular 15 with this article.

01. Stable Standalone API
At the time of the Angular 14 version release, the Angular team officially announced that they are going to remove Angular’s legacy compiler and rendering pipeline implementation to improve the developer experience and performance. For the same purpose, in Angular 14 they release the Developer Preview version of Angular Standalone API. With the help of this, developers can develop any application without defining any Ng Modules. That, also helps us to create an app with less boilerplate code which improve the performance of the applications. Now, in Angular 15, Angular Standalone API is released as a stable version as it is now graduated from the preview version.  The standalone API is not fully functional in many areas of angular framework like HttpClient, Angular Router, Elements, and many more. Now, in Angular 15, we can directly bootstrapping any application through a single component with the help of a Standalone API.
import { bootstrapApplication } from '@angular/platform-browser';
import { Component } from '@angular/core';
import { AppComponent } from'./app.component';

@Component({
    standalone: true,
    selector: 'sample-component',
    imports: [ AppComponent ],
    template: `<h1>Welcome to Angular 15</h1>`,
})
export class SampleComponent {

    // component logic
}

bootstrapApplication(SampleComponent);


As per the above example, we can use the reference of the Standalone directives or components or pipes under the import function. If we mark the component as a “standalone: true” the under the component metadata, then we do not need to declare or use that component within NgModules. Also, if we require to use any specific module within the standalone component, then we can use the import function to import that module directly within that function like “import : [module_name]”.

02. Directive Composition API
Directive Composition API is one of the new features introduced in the Angular 15 release. This feature is introduced in Angular 15 due to the popular feature request on GitHub by the developer community. With the help of this, we can reuse our code. Directive Composition API helps developers to use host elements with the existing directives and in this way, it helps us to implement code reusability functionality within the application. This feature also helps developer to save time during the development process. While we use directive composition API, that particular directive acts as a Standalone directive. It needs to be remembered that all the functionality related to the directory composition API is possible with the help of the Angular compiler.
import { Component } from '@angular/core';

@Component({
    selector: 'app-menu',
    hostDirectives: [
        HasColor,
        {
            directive: CdkMenu,
            inputs: ['cdkMenuDisabled: disabled'],
            outputs: ['cdkMenuClosed: closed']
        }
    ]
   })
class AppMenu {
}


In the above example, we can see AppMenu Component is created with the help of two different hostDirectives i.e. HasColor and CdkMenu. Due to this technical enhancement in Angular 15, we can reuse the properties of any existing directives. Here as per the example, the AppMenu component will inherit all the input, and output properties along with the business logic of HasColor Directive and input, and for CdkMenu, it will inherit the input properties and the business logic.

03. Image Directive
The concept of Image Directive (or NgOptimized Image) is first introduced in Angular 14 along with Chrome Aurora to improve the performance of image loading. After that release, developers experience around 75% of improvement in the LCP. Now, in Angular 15, the same Image directives become much more stable along with some new features. Now, in this directive, we can take benefit of the automatic generation functionality of the SRC set. It helps us to upload and return the appropriate size of the images whenever we require. Due to this, the download time of the image is reduced. Also, we can use another feature called Fill Mode (currently it is released as an experimental mode). With the help of this, we do not need to declare the image dimensions. It is quite helpful when we try to migrate the CSS-based background image to use this directive or when we don’t know the exact dimension of the image.

This directive, i.e. NgOptimized can be used directly either in the NgModule.
import { NgOptimizedImage } from '@angular/common';

// Include it in the necessary NgModule
@NgModule({
  imports: [NgOptimizedImage],
})
class AppModule {}


Also, we can use it within the Angular component directly. While we need to use the Angular Image directives within a component, we need to replace the src attribute of the image tag with ngSrc, so that the image directive can prioritize the attribute to optimize the speed of the LCP images.
import { NgOptimizedImage } from '@angular/common';

@Component({
  standalone: true
  imports: [NgOptimizedImage],
})
class MyComponent {}


04. Functional Route Concept
The angular team introduced a new concept in the implementation process of route guards in Angular 15. In the earlier version, we normally use the class-based implementation for the route guards. But now in Angular 15, it is marked as @deprecated as per the Angular documentation. A new approach called Functional Route Guards has been introduced in place of the class-based approach. By using the new approach, we need to define the functions in place of the class-based concept while defining route guards and it helps us to implement route guards in a much more efficient and streamlined way. For this purpose, we can use the inject function from the @angular/core package which helps us with the dependency injection. This implementation helps us to create a reusable and composable function that we can pass as an argument within the Angular Router’s canActivate or canActivateChild functions.

As per the Angular documentation, the benefits of the functional route guards are as follows –
    We can define the route guards and their resolvers as a JavaScript functions as well.
    It reduced the boilerplate code as functional route guards do not require to define different guard class definitions.
    Functional route guards increase flexibility as they can be defined as an inline function also.
    Performance wise functional route guards are faster as compared to class-based guards. It is because it does not require creating or initiating the separate class objects instance.

05. Http with provideHttpClient
One of the new improvements in Angular 15 is that we can now use the provideHttpClient option to use HttpClient in place of using HttpClientModule. As we know that in Angular 15, modules are becoming optional now. So, in that case, taking the support of the HTTP module is a stress. So, now we can use use the provideHttpClient() which offers the support of the HttpClient.

06. Language Service
Now, in Angular 15, we can import such components directly with the help of language services that are not either mentioned as a standalone component or within the NgModules. Now angular in-language support service provides an option called Quick Fix. Through this, we can write down our angular code much more confidently and we can use this automatic import component and its fixes in the template.

07. Dependency Injection
In Angular 15, there are some changes done in the case of Dependency Injection. They are –

  • In the case of the @Injectable() decorator, it is no more supported with the provided: _NgModule syntax. In this case, we need to use providedIn : “root”.
  • We can also use the NgModule.providers if we want to limit the dependency injection to a single NgModule.
  • Also, the syntax provided: ‘any’ is also deprecated in Angular 15.

08. Improved Stack Trace
Now, in Angular 15 we can take benefit of the better Stack Traces which help us to identify any error or the location of any error. This feature is developers for to debug any issue during the development process. Now, during the execution of any application if an error occurred, then Angular will show the development code along with the library or packages which it calls. In the earlier version, developers faced difficulties to understand the error snippers as –

  • Most of the error message-related information is generated from third-party dependencies like Angular framework, zone.js, and Rx.js.
  • Also, the error message does not provide any information about which line or block code encountered this error.

But now, after a long time of collaboration between the Angular and Google Chrome DevTool team, they integrate those third-party libraries with the help of node_modules, zone.js, etc to raise proper error messages by using stack trace. So, now through this error message information, the developer can easily identify the exact code block of that error and fix it quickly.

09. MDC-based Components
With the release of Angular 15, we can use the much more stable Angular material-based components. Now, most of the Angular material components s designed in such a way that we can use them in web applications as well. Most of the changes regarding these components are based on DOM and CSS related. Now, in Angular 15, many Angular Material components related to old implementations have been deprecated or moved to the legacy section. So, if we still want to use them then we need to use the “legacy” import option for that.
import {MatLegacyButtonModule} from '@angular/material/legacy-button';

10. Improved ES-Build Supports
In the Angular 14 release, the Angular team announced one experimental functionality support called esBuild support to enable the faster build time of the application. Now, with Angular 15, the same esBuild support is extended with some new functionality like SVG template, and file replacement. Now, it also supports the ng build –watch command. The command for upgrading the angular.json builder is:-
"builder": "@angular-devkit/build-angular:browser-esbuild",

How to Upgrade to Angular 15?
So, in the above section, we have discussed the new functionality and features of Angular 15. Now, let's discuss how we can upgrade any existing angular application to the Angular 15 version. Before going to upgrade to Angular 15, we need to know some dependencies related to Angular 15 like –

  • Angular 15 has provided support for node.js version 14.20.x, 16.13.x and 18.10.x. And it terminates the support related to version 14.[15-19].x and 16[10-12].x.
  • Angular 15 now only support TypeScript version 4.8 or older than that.


So, we can use the below commands to update Angular 14 to Angular 15 –
ng update @angular/cli @angular/core

Conclusion
This article discusses some key functionalities of Angular 15. As Angular team is majorly focusing on the performance improvement of the framework for this version like server-side rendering, code reusability, etc. This type of improvement always helps the easier learning curve more simplified. So, let's upgrade the application to the Angular 15 version and use its new features and functionality of it.



About HostForLIFE

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in