Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE.eu :: Routing in Angular

clock July 17, 2023 09:11 by author Peter

This article will discuss Angular routings and the various methods to render different components using routing.


Node Js Angular VS Code
What is Angular?
Popular open-source JavaScript framework for developing web applications is Angular. 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 provides a structured method for constructing complex web applications.
What exactly is Routing?

In web development, routing refers to the process of determining how an application responds to a particular URL or path. It involves mapping URLs to various application components or views and displaying the appropriate content based on the requested URL.

Routing enables users to navigate between various views or pages in a client-side web application, such as a single-page application (SPA) built with Angular, without actually loading a new HTML page from the server. The application instead dynamically modifies the browser's content by loading the required components and data based on the requested route.
Advantages of Routing

Routing in web applications has numerous advantages. Here are several significant benefits of using routing:

  • Improved User Experience Routing enables a fluid and interactive user experience by allowing users to navigate between various views or pages within an application without reloading the entire page.
  • With routing, only the necessary components and data for the requested route are loaded, which results in quicker page transitions.
  • Routing promotes a modular structure for an application by segregating it into distinct views or components associated with specific routes. This facilitates code reuse, separation of concerns, and easier maintenance. Each route can have its own component, making it simpler to administer and independently update distinct sections of the application.
  • Conditional Rendering and Dynamic Content: Based on the current route, routing enables conditional rendering of components. This enables you to display or conceal specific application sections based on the user's navigation path.
  • Route Parameters and Query Parameters: Passing route parameters and query parameters is supported by routing. You can transmit dynamic values in the URL, such as an ID or a username, and retrieve them in the corresponding component using route parameters. Query parameters enable the URL to receive additional data for filtering, categorizing, and other purposes.
  • Route Guards and Security Angular routing includes route guards, which are mechanisms for controlling access to particular routes based on certain conditions. Route guardians can be used for authentication, authorization, and other purposes related to security. They aid in ensuring that users can only access routes or execute actions if they satisfy the required criteria.
  • Routing supports nested or subsidiary routes, enabling you to define a hierarchical navigation structure within an application. This is especially useful when dealing with complex applications with multiple navigation levels or sections that must be encapsulated and managed independently.

Routing has a significant impact on enhancing the user experience, enhancing performance, and facilitating modular and maintainable code structures in web applications.
Routing in Angular

In a client-side web application, such as a single-page application (SPA) developed with Angular, routing enables users to navigate between various views without loading a new HTML page. The application instead dynamically modifies the browser's content by loading the required components and data based on the requested route.

Angular routing typically comprises the following components:

  • Routes: Routes define the correspondence between the URL path and the components to be rendered. Each route is defined with a corresponding URL path and component that will be displayed when that path is accessed.
  • The router interprets the current URL and loads the appropriate components based on the defined routes. It monitors URL modifications and manages navigation within the application.
  • The router outlet is a placeholder within the application's template where the current route's content is rendered.
  • Links and Navigation for Routers: Links and navigation elements, such as anchor tags (a>) or buttons, are used to initiate navigation to various routes within an application. Angular allows these elements to be decorated with directives such as routerLink to specify the intended route.

Routing example in Angular
Step 1
Install NodeJS.

Step 2
Install Angular CLI using the following command.
    npm install -g @angular/cli

Step 3
Verify NodeJS and Angular CLI are installed or not using the following commands:
    node — version



    ng version

Create a new Angular Application.
    ng new RoutingDemo

Step 4
Open the Angular application in one of the editors, like VS Code, and install the bootstrap with the help of the following command:
    npm install bootstrap

next, add the bootstrap script inside the angular.json file inside the scripts and styles section
"styles": [
"src/styles.css",
"./node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"./node_modules/bootstrap/dist/js/bootstrap.min.js"
]


Step 5
Open your terminal or command prompt and navigate to your Angular project directory. Run the following commands to generate the components:
    ng generate component home
    ng generate component about
    ng generate component contact
    ng generate component feedback
    ng generate component product
    ng generate component product-offer
    ng generate component product-updates
    ng generate component rating


Step 6
Routing Configuration:
Open the app-routing.module.ts file in your project and update the route configuration to include the newly created components.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';
import { ProductComponent } from './components/product/product.component';
import { AboutComponent } from './components/about/about.component';
import { ContactComponent } from './components/contact/contact.component';
import { ProductOfferComponent } from './components/product-offer/product-offer.component';
import { ProductUpdatesComponent } from './components/product-updates/product-updates.component';
import { RatingComponent } from './components/rating/rating.component';
import { FeedbackComponent } from './components/feedback/feedback.component';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' }, //default route
  { path: 'home', component: HomeComponent },
  {
    path: 'product/:id', component: ProductComponent,
    children: [
      {path: '', redirectTo:'updates', pathMatch:'full'},
      { path: 'offers', component: ProductOfferComponent },
      { path: 'updates', component: ProductUpdatesComponent }
    ]
  },
  { path: 'about', component: AboutComponent,
    children: [
      {path: 'rating', outlet:'rate', component:RatingComponent},
      {path: 'feedback', outlet:'feed', component:FeedbackComponent}
    ]
  },
  { path: 'contact', component: ContactComponent },
  { path: '**', component: HomeComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

This configuration maps the respective paths to their corresponding components.

In Angular, the RouterModule and Routes are key components used for configuring and managing routing in an application.

RouterModule

The RouterModule is an Angular module that provides the necessary directives, services, and functionality for implementing routing in an application.

Routes
Routes is an array that defines the routes and their configurations within the application. Each route object within the Routes array specifies the URL path and the corresponding component to be rendered when that path is accessed.

Line No. 13:
To define a default route in Angular, you can use an empty path ‘ ’ as the route path in the Routes array configuration. When the empty path is accessed, Angular will render the component associated with that route.

To redirect to a different route when the default route is accessed, you can use the redirectTo property with a target route path. Additionally, the pathMatch property can be used to define the matching strategy for the route.

Line 15 to 22:
To create a route with an id parameter for displaying product details, you can modify the routing configuration in Angular as follows:
path: 'product/:id', component: ProductComponent

In this example, we’ve added a route with the path ‘product/:id’ to represent the product details page. The :id part indicates a dynamic parameter that can be accessed in the ProductComponent.
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ProductsService } from '../../services/products.service';

@Component({
  selector: 'app-products',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  productDetail? : any;

  constructor(private route : ActivatedRoute,private productService : ProductsService){}

  ngOnInit(): void {
    let productId = this.route.snapshot.params['id'];
    this.getProductDetailById(productId)
  }

  getProductDetailById(id: number){
    this.productService.getProductDetailById(id).subscribe(res => {
      this.productDetail = res
      console.log(res)
    })
  }
}


In this code, we inject the ActivatedRoute service to access the current route’s parameters. In the ngOnInit() lifecycle hook, we retrieve the id parameter using this.route.snapshot.params[‘id’] and assign it to the productId property for later use in the component’s template.

Finally, you can navigate to the product details page by providing an id value in the URL. For example, if you have a product with an id of 123, you can navigate to http://localhost:4200/product/123 to see the product details.

The ProductComponent will be rendered with the corresponding id parameter retrieved from the URL, and you can use the productId property to display the relevant product information in the template.

To create child components, ProductOfferComponent and ProductUpdatesComponent, nested under the ProductComponent, you can modify the routing configuration in Angular as follows:

Update the Routes array in your routing module (e.g., app-routing.module.ts) to include the child routes under the ProductComponent:
{
  path: 'product/:id', component: ProductComponent,
  children: [
    {path: '', redirectTo:'updates', pathMatch:'full'},
    { path: 'offers', component: ProductOfferComponent },
    { path: 'updates', component: ProductUpdatesComponent }
  ]
}


In this updated example, we’ve added child routes to the ProductComponent. The empty path ‘ ’within the children routes corresponds to the ProductComponent as the default component to be rendered when accessing /product. The offers and updates paths map to the ProductOfferComponent and ProductUpdatesComponent, respectively.

Lines 23 to 28:

To create child components RatingComponent and FeedbackComponent nested under the AboutComponent, with named outlets for rating and feedback, you can modify the routing configuration in Angular as follows:

Update the Routes array in your routing module (e.g., app-routing.module.ts) to include the child routes under the AboutComponent with named outlets:
{
  path: 'about', component: AboutComponent,
  children: [
    {path: 'rating', outlet:'rate', component:RatingComponent},
    {path: 'feedback', outlet:'feed', component:FeedbackComponent}
  ]
}


In this updated example, we’ve added child routes to the AboutComponent and specified the named outlet's rate and feed for the RatingComponent and FeedbackComponent, respectively.

Implement the AboutComponent template (about.component.html) to include the named outlets’ placeholders. For example:
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Tenetur magni saepe sint, vel eaque veniam recusandae laboriosam numquam necessitatibus? Laborum mollitia excepturi qui. Modi corporis quasi ab minima eligendi numquam!</p>

<div class="row">
    <div class="col-md-6">
        <router-outlet name="rate"></router-outlet>
    </div>
    <div class="col-md-6">
        <router-outlet name="feed"></router-outlet>
    </div>
</div>


In this template, we’ve added two <router-outlet> placeholders with the name attribute set to ‘rate’ and ‘feed’. These placeholders will be used to render the RatingComponent and FeedbackComponent within the AboutComponent template.

Update the component files for RatingComponent and FeedbackComponent as needed.

Finally, you can navigate to the About and Child components using the named outlets. For example, to access the rating component, navigate to http://localhost:4200/about/(rate:rating//feed:feedback).

I have created an outer link, as I have shown below in the app component. But You can create a URL as per your requirement, and for that, you need appropriate router links with outlets.
<a class="nav-link" [routerLink]="['/about',{
  outlets:{
    'rate': ['rating'],
    'feed': ['feedback']
  }
}]">About</a>


Line No. 30:
In Angular, the double asterisk (**) route, also known as the wildcard route or catch-all route, is used to handle routes that do not match any predefined routes. It acts as a fallback route to handle unknown or invalid URLs within your application.

To define a wildcard route, you can add a route with the path: ‘**’ configuration at the end of your routes array. This route will be matched when no other route matches the requested URL.
{ path: '**', component: HomeComponent }

Step 7
Mention the router outlet in the app component view to conditionally render different components based on navigation.
<nav class="navbar navbar-expand-lg bg-body-tertiary">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">
      <img src="../assets/logo/coder.png" class="navlogo"/> Product Application
    </a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
      <div class="navbar-nav">
        <a class="nav-link" [routerLink]="['/about',{
          outlets:{
            'rate': ['rating'],
            'feed': ['feedback']
          }
        }]">About</a>
        <a class="nav-link" routerLink="/contact">Contact</a>
      </div>
    </div>
  </div>
</nav>

<router-outlet></router-outlet>


 

So, this is all about routing in Angular.



AngularJS Hosting Europe - HostForLIFE.eu :: How to Deploy an Angular app to Firebase?

clock July 5, 2023 09:44 by author Peter

In this article, we are going to discuss a few things about Firebase and the deployment of Angular applications. Firebase is a mobile and web development platform that provides a wide range of tools and services to help developers build high-quality applications. It was originally developed by Firebase Inc., a startup founded in 2011, and was later acquired by Google in 2014.


Features of Firebase

  • Real-time Database: Firebase provides a cloud-hosted NoSQL database that allows developers to store and sync data in real-time across multiple clients. It uses a JSON-based data model and provides powerful querying capabilities.
  • Authentication: Firebase offers authentication services, enabling developers to easily add user authentication to their applications using email and password, social media logins (such as Google, Facebook, and Twitter), and other identity providers.
  • Cloud Functions: Firebase allows developers to write and deploy serverless functions that run in response to events triggered by Firebase services or HTTP requests. This feature enables developers to extend the functionality of their applications without managing servers.
  • Cloud Storage: Firebase provides secure and scalable cloud storage for developers to store and serve user-generated content like images, videos, and other files. It offers simple APIs for uploading, downloading, and managing files.
  • Hosting: Firebase Hosting allows developers to deploy and host their web applications quickly and securely. It provides a global content delivery network (CDN) to deliver static assets and dynamic content to users with low latency.
  • Analytics: Firebase Analytics provides detailed insights into user behavior and app usage. It helps developers track key metrics, understand user engagement, and make data-driven decisions to optimize their applications.
  • Performance Monitoring: Firebase Performance Monitoring helps developers gain insights into the performance of their applications. It provides real-time monitoring, tracks network requests, and identifies performance bottlenecks.

Register an Application on Firebase

Step 1
Open the following Firebase URL:
https://console.firebase.google.com/u/0/

Step 2
Add a new project.

Step 3
Configure the project name and Google Analytics with some default settings.

Step 3
Configure the project name and Google Analytics with some default settings.

 

 

 

Step 4
Register your application after clicking on the web symbol and copying the project ID that we need for deployment.

 

Create an Angular Demo Application

Step 1
Create a new angular application.
    ng new angular-firebase-deployment

Step 2
Build and run the application.
    ng serve

Step 3
Install the Firebase tool.
    npm install -g firebase-tools

Step 4
Login to the Firebase.
    firebase login

Step 5
Initialize the firebase in your current application.
    firebase init

Firebase CLI will ask you a few questions.

Which Firebase CLI features do you want to set up for this folder?
Press space to select the required feature, then enter to confirm your choices.
Select a default Firebase project for this directory: angular-demo-5658b
Here I selected angular-demo-5658b, which I created earlier.
What do you want to use as your public directory? (public) dist/angular-firebase-deployment
configure as a single-page app (rewrite all URLs to /index.html)? (y/N) Yes
The File dist/angular-firebase-deployment/index.html already exists. Overwrite? Yes
If you select Configure files for Firebase Hosting and (optionally) set up the GitHub Action Deploy option from the list at the initial level, then you need to have a repository on GitHub, and then only you can set up and configure workflow after giving access to that particular repository.


 

Create a production build using the following command:
    ng build –aot

It will create one dist folder in your project solution. dist/angular-firebase-deployment

Step 7
Execute the following command to deploy your Angular application on Firebase:
    Firebase deploy

Step 8
Finally, open the browser and open the hosting URL.




AngularJS Hosting Europe - HostForLIFE.eu :: Simplifying Usage of trackBy in Angular Directives for Effective Item Tracking

clock June 20, 2023 10:23 by author Peter

When working with lists and data rendering in Angular, it is essential to efficiently maintain track of the rendered items. A common challenge is maintaining the integrity of the rendered objects while dynamically updating the list. By utilizing the trackBy directive, Angular provides us with syntax sugar that simplifies this endeavor. This article will examine how to leverage the power of trackBy to efficiently keep track of rendered items.

Knowledge of the trackBy Directive
Essential to Angular, the trackBy directive optimizes rendering by associating a unique identifier with each list item. Using the trackBy directive, Angular can efficiently detect changes and update only the required DOM elements, resulting in enhanced performance.

Syntax and Usage

To use trackBy, please follow these steps:

Step 1. Define a Unique Identifier: Ensure that each list item in your component has a unique identifier. This is possible by incorporating an id property into your data objects.

export interface Item {
  id: number;
  // Other properties
}

// Example data
items: Item[] = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
  // Additional items
];

Step 2. Specify the trackBy Function: Next, create a method in your component that acts as the trackBy function. This function will be responsible for returning the unique identifier for each item.
trackByFn(index: number, item: Item): number {
  return item.id;
}

Step 3.  Apply trackBy in Template: In your HTML template, apply the trackBy directive by binding it to the ngFor loop.
<ng-container *ngFor="let item of items; trackBy: trackByFn">
  <!-- Render item here -->
</ng-container>

The benefits of using the trackBy Directive offer
Improved Performance: By associating a unique identifier with each item, Angular can efficiently track changes and update only the affected elements, resulting in optimized rendering performance.

Reduced DOM Manipulation: With trackBy, Angular avoids unnecessary DOM manipulations by reusing existing elements when the data changes, leading to a smoother user experience.

Simplified Syntax: The syntax sugar provided by the trackBy directive simplifies the usage and implementation of item tracking in Angular, making the code more readable and maintainable.

By utilizing the syntax sugar of Angular directives, specifically the trackBy directive, we can easily maintain good track of rendered items in our Angular applications. By following the steps outlined in this article, you can optimize performance, reduce unnecessary DOM manipulations, and simplify the codebase. Leveraging the power of trackBy, you can build responsive and efficient Angular applications with ease.




AngularJS Hosting Europe - HostForLIFE.eu :: Sorting Based on Selection in Check Box using Pipe

clock June 8, 2023 09:58 by author Peter

To sort an array of objects by a checkbox selection in a column using a custom pipe in Angular, you can modify the checkbox-selection.pipe.ts file as follow
Custom Pipe (checkbox-selection.pipe.ts)


To generate pipe, use the following comment.

ng g p CheckboxSelectionPipe
    g- stands for generate
    p- stands for pipe

CheckboxSelectionPipe - use your custom pipe name instead of [checkboxslectionpipe]

In Pipe declaration, we can define the filter's name (pipe); when the pipe is true, the pipe is pure, meaning that the transform() method is invoked only when its input arguments change. Pipes are pure by default.

In the transform() method, we can pass the array which needs to be filtered.

Code Explanation
In the SelectedItems array, we will filter the collection based on the selected property in the collection. If the selected property was setted to true means, it will filter into SelectedItems.
In the UnSelectedItems array, we will filter the collection based on the selected property in the collection. If the selected property was setted to false means, it will filter into UnSelectedItems.

Here I have used the spread operator (...) that will allow us to quickly copy all or part of an existing array or object into another array or object.

While returning, it will merge Selected and unselected items.
@Pipe({
  name: 'orderByCheckboxSelection',
  pure:false

})
export class CheckboxSelectionPipe implements PipeTransform {

  transform(list: any): any {
    if (!list) {
      return [];
    }

    // Sort the items based on whether they are selected or not
    let selectedItems = list.filter(item => item.selected);
    let unselectedItems = list.filter(item => !item.selected);

    return [...selectedItems, ...unselectedItems];
  }

}


App.Module.ts for a particular module
Register the custom pipe in the module where you want to use it. For example, open the app.module.ts file and import and add CheckboxSelectionPipe to the declarations array.
@NgModule({
  declarations: [....,....],
  imports: [
    CheckboxSelectionPipe
  ],
  providers: [ ....]


App.Component.html
By providing the CheckBoxSelection pipe to the array needed to sort, you can sort the array based on that property's checkbox selection.
<div *ngFor="let date of collection | orderByCheckboxSelection ">
 ....
....
</div>



AngularJS Hosting Europe - HostForLIFE.eu :: Dynamic JSON Data Handling in Angular

clock May 30, 2023 09:16 by author Peter

You can take the following actions to handle the provided JSON example dynamically in an Angular application:
"Data": ["confidence": 0.9983, "label": "height", "value": "5 FT 7 IN"; "confidence": 0.9971, "label": "squad", "value": "Team A"

Step 1
Create an Angular component: Run the ng produce component dynamicHandling command to create a new component using the Angular CLI.

Step 2
Import the HttpClientModule from @angular/common/http in the app.module.ts file to initiate HTTP queries.
'@angular/common/http' import HttpClientModule;

export class AppModule @NgModule("imports: [ HttpClientModule ], //...")

Step 3
To retrieve the JSON data, send an HTTP request: Import the HttpClient and issue an HTTP GET request to the component's TypeScript file (dynamic-handling.component.ts) to obtain the JSON data.

Component, OnInit, import from '@Angular/core';
'@angular/common/http' import HttpClient;

@Component('app-dynamic-handling', './dynamic-handling.component.html', and './dynamic-handling.component.css') export class DynamicHandlingComponent implements OnInit with the following parameters: jsonData: any;

  private http: HttpClient constructor

  This.http.getany>('your_api_endpoint') in ngOnInit() returns void.(data => subscribe) this.jsonData = data.Data; ); ;



Step 4
To loop through the JSON data in the template, use ngFor: Utilize the ngFor directive in the component's HTML file (dynamic-handling.component.html) to cycle through the jsonData array and dynamically display the results.

"let item of jsonData" in the div *ngFor attribute.'item.label': 'item.value' '/p' '/div'

Step 5
Include the element in the primary template: To display the dynamic handling component, include the app-dynamic-handling> and /app-dynamic-handling> tags in the app.component.html file.
App-dynamic-handling in div, app-dynamic-handling out of div.

The real API endpoint from which you may obtain the JSON data should be substituted for "your_api_endpoint" in Step 3.

As indicated in Steps 2 and 5, be sure to import the HttpClientModule into the app.module.ts file and include the dynamic handling component in the app.component.html main template.

Once the component and template have been configured, the Angular application will issue an HTTP request to retrieve the JSON data and use the ngFor directive in the template to dynamically display the information.



AngularJS Hosting Europe - HostForLIFE.eu :: How to Sort Column (Orderby) Based on Date in Angular 13 using Pipe?

clock May 25, 2023 13:02 by author Peter

To sort an array of objects by a particular date column in ascending or descending order using a custom pipe in Angular, you can modify the date-sort.pipe.ts file as follows:
Custom Pipe (date-sort.pipe.ts)


In Pipe declaration, we can define the name of the filter (pipe), When pipe is true, the pipe is pure, meaning that the transform() method is invoked only when its input arguments change. Pipes are pure by default.

In the transform() method, we can pass the array which needs to be filtered. Property parameter can as based on which date column we need to sort; ordering 'asc' | 'desc' can be also passed.

@Pipe({
  name: 'orderByDate',
  pure:false

})
export class OrderByDatePipe implements PipeTransform {

  transform(array: any[], property: string, order: 'asc' | 'desc'): any[] {
    if (!Array.isArray(array) || !property) {
      return array;
    }

    array.sort((a, b) => {
      const dateA = new Date(a[property]);
      const dateB = new Date(b[property]);

      if (order === 'asc') {
        return dateA.getTime() - dateB.getTime();
      } else {
        return dateB.getTime() - dateA.getTime();
      }
    });

    return array;
  }
}


App.Module.ts for a particular module

Register the custom pipe in the module where you want to use it. For example, open the app.module.ts file and import and add OrderByDatePipe to the declarations array:
@NgModule({
  declarations: [....,....],
  imports: [
    OrderByDatePipe
  ],
  providers: [ ....]


For use across Application

1. We can use Share.Module.ts, Register the custom pipe in share module,
@NgModule({
  declarations: [
    OrderByDatePipe
  ],
  imports: [
    CommonModule
  ]
  ,exports:[
   OrderByDatePipe

  ]
})


2. We can import ShareModule in whether we want to use it inside any module.
@NgModule({
  declarations: [...,.... ],
  imports: [
    .....
    SharedModule,
    ....
  ],
  providers: [ .....]


App.Component.html
    In your component's template, pass the desired date column and order ('asc' or 'desc') as parameters to the OrderByDatePipe :
    Make sure to replace 'scheduleStartDate' with the actual name of the date column in your array of objects.

By providing the specific property/column to the orderByDate pipe, you can sort the array based on that property's date values in either ascending or descending order.
<div *ngFor="let schedule of CurrentSchedule | orderByDate:'scheduleStartDate':'asc'">
 ....
....
</div>
 <div *ngFor="let schedule of CurrentSchedule | orderByDate:'scheduleStartDate':'desc'">
 ....
....
</div>



AngularJS Hosting Europe - HostForLIFE.eu :: Real-Time Communication Made Simple: Angular Demonstrating Web Sockets

clock May 23, 2023 07:12 by author Peter

Web Sockets
Web sockets are a protocol that facilitates bidirectional, full-duplex communication between clients and servers over a single, persistent connection. In contrast to conventional HTTP requests, which are stateless and request-response based, web sockets enable event-driven communication in real time. They are especially useful for applications requiring real-time updates, such as messaging applications, collaborative tools, and real-time dashboards.

Setting Up an Angular Project
To begin using web sockets in Angular, we must create a new project. Let's utilize the Angular CLI to scaffold the application's structure and install any necessary dependencies. Open your terminal or command prompt and proceed as follows:

Install Angular CLI if it is not already installed.

npm install -g @angular/cli

Step 2. Create a new Angular project.
ng new websocket-demo
cd websocket-demo


Establishing a Web Socket Connection
Now that we have our Angular project set up let's establish a web socket connection. We'll create a service that wraps the WebSocket API and handles the connection lifecycle. Open the terminal/command prompt and navigate to the project's root directory. Then, follow these steps.

1. Generate a WebSocket service.
ng generate service websocket

2. Open the newly generated service file (websocket.service.ts) and replace its content with the following code.
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class WebsocketService {
  private socket: WebSocket;

  constructor() { }

  connect(): void {
    this.socket = new WebSocket('wss://your-websocket-url');

    this.socket.onopen = () => {
      console.log('WebSocket connection established.');
    };

    this.socket.onmessage = (event) => {
      console.log('Received message:', event.data);
    };

    this.socket.onclose = (event) => {
      console.log('WebSocket connection closed:', event);
    };

    this.socket.onerror = (error) => {
      console.error('WebSocket error:', error);
    };
  }

  sendMessage(message: string): void {
    this.socket.send(message);
  }

  closeConnection(): void {
    this.socket.close();
  }
}


3. Replace 'wss://your-websocket-url' in the connect() the method with the actual WebSocket URL you want to connect to.

Sending and Receiving Data

With our web socket service in place, we can now send and receive data between the client and server. Open the component where you want to use the web socket service (e.g., app.component.ts) and follow these steps.

Import the WebSocket service
import { Component } from '@angular/core';
import { WebsocketService } from './websocket.service';

@Component({
  selector: 'app-root',
  template: `
    <button (click)="sendMessage()">Send Message</button>
  `
})
export class AppComponent {
  constructor(private websocketService: WebsocketService) {}

  sendMessage(): void {
    const message = 'Hello, WebSocket!';
    this.websocketService.sendMessage(message);
  }
}

In the same component file (e.g., app.component.ts), add the following code to receive messages from the server.
@Component({
  // Component configuration...
})
export class AppComponent implements OnInit {
  receivedMessages: string[] = [];

  constructor(private websocketService: WebsocketService) {}

  ngOnInit(): void {
    this.websocketService.connect();
    this.websocketService.messageReceived.subscribe((message: string) => {
      this.receivedMessages.push(message);
    });
  }

  sendMessage(): void {
    const message = 'Hello, WebSocket!';
    this.websocketService.sendMessage(message);
  }
}

In the component template (app.component.html), display the received messages.
<button (click)="sendMessage()">Send Message</button>

<ul>
  <li *ngFor="let message of receivedMessages">{{ message }}</li>
</ul>

Now, when the sendMessage() the method is called, it will send a message to the server using the web socket service. The received messages from the server are stored in the receivedMessages array and displayed in the component template.

Handling Errors and Disconnections

To handle errors and disconnections gracefully, let's make some modifications to our existing code. Open the websocket.service.ts file and follow these steps,

-  Import the Subject class from RxJS to handle the stream of received messages. Add the following line at the top of the file after the existing imports.
import { Subject } from 'rxjs';

-  Inside the WebsocketService class, declare a new messageReceived property of type Subject<string>. This will be used to emit and subscribe to the received messages:
messageReceived: Subject<string> = new Subject<string>();

-  In the onmessage event handler, modify the code to emit the received message through the messageReceived subject.
this.socket.onmessage = (event) => {
  const message = event.data;
  console.log('Received message:', message);
  this.messageReceived.next(message);
};


By implementing these changes, we are now using the messageReceived subject to emit and subscribe to the received messages in our Angular component. This allows us to handle and display the messages in real time.

In this article, we have explored how to implement web sockets in an Angular project to enable real-time communication between clients and servers. We covered the fundamentals of web sockets, including setting up an Angular project, establishing a web socket connection, sending and receiving data, and handling errors and disconnections.



AngularJS Hosting Europe - HostForLIFE.eu :: Implementing Different Chart Types In Angular

clock August 1, 2022 09:36 by author Peter

In current day, data is everywhere and is an important part of our lives. We collect, send, analyse, and do lots of other things with data. Data in itself is not visually appealing, but we can make it beautiful. Chart is one such thing that can make data look beautiful & easier to understand / analyse. We can use different chart types to show data depending on the type of data we are showing. In this article, we will see how to add, configure and use different chart types in Angular using CanvasJS angular charts.

Adding CanvasJS angular chart to project
Let's start by adding CanvasJS angular chart component to the project. Download the component from the official download page. Copy the chart component files to the project. Generally, these files are kept under assets directory. Once it's copied, import & register the modules.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

import * as CanvasJSAngularChart from './assets/canvasjs.angular.component';
var CanvasJSChart = CanvasJSAngularChart.CanvasJSChart;

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


As the modules are registered, you can start creating chart. Let's create & display simple column chart in angular.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: '<canvasjs-chart [options]="chartOptions"></canvasjs-chart>'
})
export class AppComponent {
    chartOptions = {
      title: {
          text: "Angular Column Chart"
      },
      data: [{
        type: "column",
        dataPoints: [
            { label: "apple",  y: 10  },
            { label: "orange", y: 15  },
            { label: "banana", y: 25  },
            { label: "mango",  y: 30  },
            { label: "grape",  y: 28  }
        ]
      }]
    }
}

Here we first imported the CanvasJS chart component & then define the options for the chart. CanvasJS takes data to be plotted along with other chart element customization options as 'chart-options'. In the above example, you can observe labels are passed to each datapoint which are shown below every bar (vertical bar charts are called as column chart). The same can be changed to horizontal bar or line or pie by just changing type property. The data is an array of objects where each dataseries is an object - this means if you pass multiple objects, it creates chart with multiple series.

Line Chart

Line chart is a way to represent data in the form of line. Often they are used to show the trend or to compare two different data sets. In the above simple chart that you created, just change type property to 'line' & that should create a line chart instead of column. CanvasJS has different kinds of lines - regular line, spline (similar to line except that the line is smooth), step-line (similar to line but line is in the form of steps/staircase).
chartOptions = {
  title: {
      text: "Angular Line Chart"
  },
  data: [{
    type: "line",
    dataPoints: [
        { label: "apple",  y: 10  },
        { label: "orange", y: 15  },
        { label: "banana", y: 25  },
        { label: "mango",  y: 30  },
        { label: "grape",  y: 28  }
    ]
  }]
}

Just by filling the region between the base and the datapoints value, it create area chart. Component supports different area forms like area, range area, stacked area & gets clubbed with different types of line to create more combinations.

Bar Chart
In bar chart, data is represented in the form of rectangles - vertical bars / horizontal bars. Syntax is same as line but type field takes different value. Bars can be vertical called column chart or horizontal called bar chart. CanvasJS angular component has different kinds of bar charts like bar, range bar, stacked bar, stacked bar 100%, column, range column, stacked column, stacked column 100% & waterfall.
chartOptions = {
  title: {
    text: "Angular Bar Chart"
  },
  data: [{
  type: "bar",
  dataPoints: [
    { label: "apple",  y: 10  },
    { label: "orange", y: 15  },
    { label: "banana", y: 25  },
    { label: "mango",  y: 30  },
    { label: "grape",  y: 28  }
  ]
  }]
}

Pie Chart
Pie chart is probably the most commonly used chart where datapoint is represented as slices of the pie. Each slice will show the relational proportion between the data. Pie chart can further be modified to have a hollow space in the centre making it look like a donut & hence this type of chart is called doughnut / donut chart.
chartOptions = {
  title: {
    text: "Angular Pie Chart"
  },
  data: [{
  type: "pie",
  dataPoints: [
    { label: "apple",  y: 10  },
    { label: "orange", y: 15  },
    { label: "banana", y: 25  },
    { label: "mango",  y: 30  },
    { label: "grape",  y: 28  }
  ]
  }]
}


Financial Chart
Financial chart is generally used to show the stock data / trades. These are most commonly used chart type in stock, forex, shares, etc. These charts will generally be dynamic charts - keeps updating latest data automatically by fetching data from some API.
chartOptions = {
  title: {
    text: "Angular Financial Chart"
  },
  data: [{
  type: "candlestick",
  dataPoints: [
    { label: "Jan", y: [1341.55, 1503.21, 1341.55, 1434.22] },
    { label: "Feb", y: [1462.00, 1532.10, 1271.00, 1339.32] },
    { label: "Mar", y: [1351.60, 1410.15, 1013.53, 1162.81] },
    { label: "Apr", y: [1122.00, 1359.98, 1079.81, 1348.66] },
    { label: "May", y: [1328.50, 1441.00, 1299.00, 1428.92] },
    { label: "Jun", y: [1418.39, 1475.94, 1347.01, 1413.60] },
    { label: "Jul", y: [1411.09, 1586.98, 1409.81, 1482.95] },
    { label: "Aug", y: [1486.64, 1659.21, 1458.65, 1634.18] },
    { label: "Sep", y: [1636.63, 1733.18, 1406.55, 1469.59] },
    { label: "Oct", y: [1484.27, 1687.00, 1436.00, 1621.01] },
    { label: "Nov", y: [1628.16, 1818.06, 1616.03, 1760.73] },
    { label: "Dec", y: [1774.36, 1847.19, 1699.00, 1751.88] }
  ]
  }]
}


More Chart Types & Additional Examples
You can check out CanvasJS angular charts gallery page where more working examples are shown with varieties of use-cases & customization. Also complete customization options can be found on CanvasJS's documentation section.

Conclusion
CanvasJS angular chart component makes it easy to showcase varieties of chart types in your application and dashboard. It also supports dynamic charts making it easier to automate to show latest data always.



AngularJS Hosting Europe - HostForLIFE.eu :: Angular Data Binding

clock October 16, 2020 07:42 by author Peter

Binding is basically the process of connecting data between the view of your application and it's code behind.
In Angular, the view of the application is the HTML page and the code behind is the Component class written in typescript code.
 
There are different types of data binding in Angular,
 
Component to View using interpolation
This is one of the ways of bindings provided by the Angular framework. For this one, we need to have a class level property in our Component class which we use in our HTML using double curly braces.
 
For example, the below code snippet shows a piece of code in the component class. There are 3 properties: department, imgURL and
showspinner, out of which imgURL and showspinner are already initialized, whereas department is just declared.
    department: Any;  
    imgURL: string = "assets/photos/Department.jpg";  
    showSpinner: boolean = false;   


In our HTML file, these properties are used inside double curly braces to render these values directly on the browser. In our case, the imgURL represents the source of the image so that has to be used in the below manner, as shown in the below code snippet.
    <image src = {{imgURL}} >  

When the application gets rendered on the browser, {{imgURL}} gets replaced by assets/photos/Department.jpg.
 
In the real time application, this property is initialized dynamically at runtime.
 
Component to View using property binding
Just like interpolation, this is another type of one way binding. Just like the prior one, in property binding also, we need a class level property that has to be bound with an HTML control on the View. However, the syntax is a little different.
 
Let's use the same example to apply to property binding.
    department: Any;  
    imgURL: string = "assets/photos/Department.jpg";  
    showSpinner: boolean = false;  

To use the property binding we need to use the below syntax. We need to enclose the property of the HTML control inside the square braces and enclose the Component property inside the quotes.
    <image [src] = 'imgURL' >  

Note
While rendering the data on UI, interpolation converts the data into string, whereas property binding does not change the type and renders it as it is.
 
View to Component using event binding
 
This type of binding is used to bind data from View to Component i.e. from the HTML page to the Component class. This one is similar to the events of simple javascript. It can either be a simple click event, a keyup, or any other. The only difference is that the events in Angular have to be put inside circular braces, the rest all is same.
 
As shown in the below code snippet, there are 3 buttons with their respective click events. The methods handling those events are in the code behind file.
    <button (click) = 'addDepartment()' >Add </button>  
    <button (click) = 'editDepartment()' >Edit </button>  
    <button (click) = 'deleteDepartment()' >Delete </button>  

To Bind View and Component Simultaneously (two-way binding)
 
This type of binding is a little different from other frameworks. The two-way binding keeps the property in the Component class and the value of the HTML control in sync. Whenever we change the value of HTML control, the value of the property of the Component class also
changes.
 
To implement this type of binding in Angular, we use a special directive with a little bit different of a syntax.
    <input required [(ngModel)] = 'departmentName' name = 'departmentName' >  

As you can see in the above code snippet, a directive ngModel has been used inside 2 types of braces. The two braces signify two different bindings. The square brace is for property binding that we discussed as the second type and the circular is for event binding, the third one
that we discussed.
 
Lets talk a little about this textbox, whenever there is any change in the value of this textbox an event gets triggered, and by means of the event binding the value gets passed to the Component property and it gets updated and similarly whenever there is any change in the property value, the value of the textbox will also get updated by means of property binding.

The Component property associated with this textbox in the above code is departmentName.
 
Take an example, when we are fetching some data by making an API call, at the beginning the textbox won't have any value but as soon as the value of the property in the Component class gets updated, the value of textbox will also get updated simultaneously.
 
Note
In order to use [(ngModel)] for two-way binding, the name attribute is a must. The Angular framework internally uses the name attribute to map the value of HTML control with the Component property.

HostForLIFE.eu AngularJS 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 :: How to Create Strong Password for AngularJS Pages?

clock September 18, 2020 08:28 by author Peter

In this post, let me explain you how to create strong password for AngularJS. For choosing a password we need combination of special characters, Capital letter , small letters, digits etc to make it strong. Write the following code:

    <!DOCTYPE html> 
    <html> 
    <head> 
        <title>Strong Password for Angular UI Pages</title>            
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>   
        <script> 
            var app = angular.module("myApp", []); 
            app.controller("myCtrl", function ($scope) {        
                var strongRegularExp = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");        
                var mediumRegularExp = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");        
                $scope.checkpwdStrength = { 
                    "width": "150px", 
                    "height": "25px", 
                    "float": "right" 
                };        
                $scope.validationInputPwdText = function (value) { 
                    if (strongRegularExp.test(value)) { 
                        $scope.checkpwdStrength["background-color"] = "green"; 
                        $scope.userPasswordstrength = 'You have a Very Strong Password now'; 
                    } else if (mediumRegularExp.test(value)) { 
                        $scope.checkpwdStrength["background-color"] = "orange"; 
                        $scope.userPasswordstrength = 'Strong password, Please give a very strong password';  
                    } else { 
                        $scope.checkpwdStrength["background-color"] = "red"; 
                        $scope.userPasswordstrength = 'Weak Password , Please give a strong password'; 
                    }                  
};        
           }); 
        </script> 
    </head> 
    <body ng-app="myApp"> 
        <div ng-controller="myCtrl" style="border:5px solid gray; width:800px;"> 
            <div> 
                <h3>Strong Password for Angular UI Pages </h3> 
            </div> 
            <div style="padding-left:25px;">                  
<div ng-style="checkpwdStrength"></div> 
                <input type="password" ng-model="userPassword" ng-change="validationInputPwdText(userPassword)" class="class1" /> 
                <b> {{userPasswordstrength}}</b> 
            </div> 
            <br /> 
            <br /> 
            <br /> 
        </div> 
    </body> 
    </html> 

HostForLIFE.eu AngularJS 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.



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