Showing posts with label Angular. Show all posts
Showing posts with label Angular. Show all posts

Tuesday 21 March 2023

Mastering Data Filtering with Complex Objects: Strategies and Techniques


Mastering Data Filtering with Complex Objects: Strategies and Techniques


Hi Everyone, The filter logic is a mechanism that allows you to search and retrieve specific data from a larger dataset. The filter function takes two arguments: the data to filter and a filter parameter that defines the search criteria. The function returns a subset of the original data that matches the filter criteria.So lets understand how we can acheive "Data Filtering with Complex Objects".

In the case of the Angular Material table, the filter logic is used to search for specific data in a table by applying a search filter to one or more columns. When the user enters a search query, the filter logic is triggered and filters the table data based on the search criteria. The filtered data is then displayed in the table.

The filter logic can be implemented in many ways, depending on the specific use case.
Now consider this JSON array which contains nested array.


[

{

deviceUUID: ‘80a9b8a2–3a2c’,

ipAddress: ‘2.2.2.67’,

deviceParameter: {

deviceName: ‘device44’,

unitIdentifier: 1,

port: 502,

},

isConnected: false,

isSerial: false,

details: null,

Type: ‘Ethernet’,

},

{

deviceUUID: ‘80a9b8a2–3a2c’,

ipAddress: ‘2.2.2.67’,

deviceParameter: {

deviceName: ‘device46’,

unitIdentifier: 1,

port: 503,

},

isConnected: false,

isSerial: false,

details: null,

Type: ‘Ethernet’,

},

{

deviceUUID: ‘80a9b8a2–3a2c’,

ipAddress: ‘2.2.2.67’,

deviceParameter: {

deviceName: ‘device48’,

unitIdentifier: 1,

port: 505,

},

isConnected: false,

isSerial: false,

details: null,

Type: ‘Ethernet’,

}

];




So if our requirement says that filter the object on ‘device name’ or ‘port’ that is not quite possible because that mat-filter is works with straight forward object but we can also achieve this things first understand how we can do that

The inner object search is different because it requires accessing a nested property within each object of an array, whereas other searches involve searching for a property directly in each object of the array. This requires a different approach to extract the nested property and perform the search.

So here we use ‘ filterPredicate’ to search nested object : The filterPredicate is used to search nested objects in a mat-table because the default filter behaviour in Angular Material only works on flat objects with simple properties. When dealing with more complex data structures like nested objects, we need to write their own custom filtering logic to extract the nested data they want to filter on. The filterPredicate function provides a way to do this by allowing us to write own filtering logic based on the nested data structure of their data source.

So lets begin with our example.


first create a one project which have preinstall angular material and all dependencies that is required to run angular mat-table to run

2. Here is my app.component.html code to declare mat-table

<mat-label>Filter</mat-label>

<input matInput (keyup)=”applyFilter($event)” placeholder=”Ex. ium” #input>

<table mat-table [dataSource]=”dataSource” matSort matSortActive=”deviceName” matSortDirection=”asc” matSortDisableClear>

<ng-container matColumnDef=”deviceName”>

<th mat-header-cell *matHeaderCellDef mat-sort-header> Device Name </th>

<td mat-cell *matCellDef=”let device”> {{device.deviceParameter.deviceName}} </td>

</ng-container>

<ng-container matColumnDef=”unitIdentifier”>

<th mat-header-cell *matHeaderCellDef> Unit Identifier </th>

<td mat-cell *matCellDef=”let device”> {{device.deviceParameter.unitIdentifier}} </td>

</ng-container>

<ng-container matColumnDef=”port”>

<th mat-header-cell *matHeaderCellDef> Port </th>

<td mat-cell *matCellDef=”let device”> {{device.deviceParameter.port}} </td>

</ng-container>

<tr mat-header-row *matHeaderRowDef=”displayedColumns”></tr>

<tr mat-row *matRowDef=”let row; columns: displayedColumns;”></tr>

</table>

3. Replace the component.ts code with this

import { Component } from ‘@angular/core’;

import { MatTableDataSource } from ‘@angular/material/table’;

export interface Device {

deviceUUID: string;

ipAddress: string;

deviceParameter: {

deviceName: string;

unitIdentifier: number;

port: number;

};

isConnected: boolean;

isSerial: boolean;

details: any;

Type: string;

}

const DEVICE_LIST: Device[] = [

{

deviceUUID: ‘80a9b8a2–3a2c’,

ipAddress: ‘2.2.2.67’,

deviceParameter: {

deviceName: ‘device44’,

unitIdentifier: 1,

port: 502,

},

isConnected: false,

isSerial: false,

details: null,

Type: ‘Ethernet’,

},

{

deviceUUID: ‘80a9b8a2–3a2c’,

ipAddress: ‘2.2.2.67’,

deviceParameter: {

deviceName: ‘device46’,

unitIdentifier: 1,

port: 503,

},

isConnected: false,

isSerial: false,

details: null,

Type: ‘Ethernet’,

},

{

deviceUUID: ‘80a9b8a2–3a2c’,

ipAddress: ‘2.2.2.67’,

deviceParameter: {

deviceName: ‘device48’,

unitIdentifier: 1,

port: 505,

},

isConnected: false,

isSerial: false,

details: null,

Type: ‘Ethernet’,

}

];

@Component({

selector: ‘app-root’,

templateUrl: ‘./app.component.html’,

styleUrls: [‘./app.component.css’]

})

export class AppComponent {

title = ‘MaterialDesign’;

displayedColumns: string[] = [‘deviceName’, ‘unitIdentifier’, ‘port’];

dataSource = new MatTableDataSource<Device>(DEVICE_LIST);

constructor() {

// this.dataSource = new MatTableDataSource<Device>(DEVICE_LIST);

this.dataSource.filterPredicate = (data: Device, filter: string) => {

const searchString = filter.trim().toLowerCase();

return data.deviceParameter.deviceName.toLowerCase().includes(searchString) ||

data.deviceParameter.port.toString().toLowerCase().includes(searchString);

};

}

applyFilter(event: Event) {

const filterValue=(event.target as HTMLInputElement).value;

this.dataSource.filter = filterValue.trim().toLowerCase();

}

}




4. Replace the app.module.ts file with following code :


import { NgModule } from ‘@angular/core’;

import { BrowserModule } from ‘@angular/platform-browser’;

import { AppRoutingModule } from ‘./app-routing.module’;

import { AppComponent } from ‘./app.component’;

import { BrowserAnimationsModule } from ‘@angular/platform-browser/animations’;

import { MatSlideToggleModule } from ‘@angular/material/slide-toggle’;

import { MatButtonModule } from ‘@angular/material/button’;

import { MatTableModule } from ‘@angular/material/table’;

import { MatPaginatorModule } from ‘@angular/material/paginator’;

import { MatSortModule } from ‘@angular/material/sort’;

import { MatFormFieldModule } from ‘@angular/material/form-field’;

@NgModule({

declarations: [

AppComponent,

],

imports: [

BrowserModule,

AppRoutingModule,

BrowserAnimationsModule,

MatSlideToggleModule,

MatButtonModule,

MatTableModule,

MatPaginatorModule,

MatSortModule,

MatFormFieldModule

],

providers: [],

bootstrap: [AppComponent]

})

export class AppModule { }

Now understand how this filterPredicate function works. please again review this code


constructor() {

this.dataSource.filterPredicate = (data: Device, filter: string) => {

const searchString = filter.trim().toLowerCase();

return data.deviceParameter.deviceName.toLowerCase().includes(searchString) ||

data.deviceParameter.port.toString().toLowerCase().includes(searchString);

};

}

applyFilter(event: Event) {

const filterValue=(event.target as HTMLInputElement).value;

this.dataSource.filter = filterValue.trim().toLowerCase();

}

The function is being assigned to the filterPredicate property of a MatTableDataSource object.

It takes two arguments: data and filter. data represents a single element in the data source, while filter is the value entered by the user to filter the data.

searchString is a variable that is created by trimming any whitespace and converting the filter string to lowercase.

The function returns a boolean value that determines whether or not the data object should be included in the filtered data source. It does this by checking if the lowercase deviceName or lowercase port of the deviceParameter object of the data object includes the searchString.

If the searchString is found in either deviceName or port, the function returns true, indicating that the data object should be included in the filtered data source.

If the searchString is not found in either deviceName or port, the function returns false, indicating that the data object should be excluded from the filtered data source.

Please feel free to check out my GitHub repository at the following link, where you can find the code for the NestedObjectFilterMatTable:

Filter Nested Complex object

I would greatly appreciate it if you could take a look at it and let me know if you have any feedback or suggestions. Thank you very much for your time and consideration.

Saturday 11 March 2023

This version of CLI is only compatible with Angular versions ^15.0.0, but Angular version 8.1.3 was found instead.

When working on an existing Angular project, I typically review all the project details and execute the "npm install" command in the terminal to install all the necessary modules. However, upon attempting to run the project using a CLI command, an error is displayed.

This version of CLI is only compatible with Angular versions ^15.0.0, but Angular version 8.1.3 was found instead.





 
Following that, I navigated to the project's package.json file and discovered that the project was developed using Angular version 8.1.3.


There are two potential ways to address this issue:


1.       Upgrade your Angular project to a newer version that aligns with the Angular CLI version you have installed.

2.       Downgrade the Angular CLI version to a version that supports your current Angular version.


Let's delve into each of these methods in more detail.

·         upgrade your project to use a newer version of Angular : To upgrade your Angular project, you can follow the steps outlined in the Angular documentation for upgrading to a newer version: https://update.angular.io/

 

General step that to be followed to update the project

a.       Check the compatibility: Review the official Angular documentation to ensure that the version you are upgrading to is compatible with your application.

b.       Update Angular CLI: Update the Angular CLI to the latest version by running the following command in your terminal or command prompt: ng update @angular/cli

c.       Update Angular Core: Update the Angular Core package to the latest version by running the following command in your terminal or command prompt: ng update @angular/core

d.       Update dependencies: Review and update other dependencies in your package.json file, as necessary.

e.       If we are using any third party library let say material and other then we need to be update that with newer version

f.       Fix any errors: Review your application and fix any errors that occur as a result of the updates.

g.        Run tests: Run your application's tests to ensure that everything is working as expected.

h.       Update Angular Language Service: If you are using Angular Language Service, update it to the latest version by running the following command in your terminal or command prompt: ng update @angular/language-service

i.       Update other Angular packages: If you are using any other Angular packages, such as @angular/router or @angular/forms, update them to the latest version by running the appropriate ng update command.


·         downgrade the Angular CLI version : To downgrade the version of our project we can run the following commands on CLI.


npm uninstall -g @angular/cli

 

Then, install a specific version of the CLI that is compatible with your Angular version using the following command:

 

npm install -g @angular/cli@<version>

 

Replace <version> with the version number of the CLI that is compatible with your Angular version, for example:

 

npm install -g @angular/cli@8.1.3

 

After installing the compatible version of the CLI, you should be able to use it with your current version of Angular.

 

In my personal opinion, if you are assign or work with previous version of angular project you must try to downgrade your angular CLI version because sometime upgrading will causing issue because some of the libraries are not compatible with newer version.


Friday 10 March 2023

Missing Helper ‘__spreadArray’:Upgrading ‘tslib’ Required or This syntax requires an imported helper named ‘__spreadArray’ which does not exist in ‘tslib’. Consider upgrading your version of ‘tslib’.ts

Fixing Console Error: Troubleshooting Loom Chrome Extension for Running Projects

 As the colors of Holi fade, I extend my warmest greetings to all. May you be blessed with good health and happiness in the days ahead.

Today, we’ll explore the purpose of the ‘__spread’ array and why it causes errors in TypeScript (while it works fine in JavaScript). I’ll provide an example to illustrate the issue and then share the solution I found while developing this feature in TypeScript.

Let’s start by discussing the purpose of the __spreadArray function.

The ‘__spreadArray’ helper function is used in TypeScript code that uses the spread operator (…) on an array. The spread operator is used to “spread” the elements of an array into a new array.

However, when using the spread operator with an empty array, it can sometimes cause issues in TypeScript. For example, consider the following code:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combinedArr = […arr1, …arr2];

This code will work fine in JavaScript, but in TypeScript, it will produce an error,

error TS2532: Object is possibly ‘undefined’.

Now that we have a better understanding of the __spreadArray function, we can delve into the reasons why this error occurs specifically in TypeScript.

This error occurs because TypeScript is not sure if the arrays being spread are empty or not. To avoid this issue, the ‘__spreadArray’ helper function can be used instead of the spread operator when combining arrays. The ‘__spreadArray’ function takes two arguments: the first is the initial array, and the second is the array to be added.

Now, let’s move on to the solution. There are two ways to resolve this issue when working with TypeScript and Angular.

  1. By importing __spreadArray in our .ts file: Here is an example of how ‘__spreadArray’ can be used to combine arrays safely in TypeScript:
    import { __spreadArray } from ‘tslib’;

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const combinedArr = __spreadArray(__spreadArray([], arr1), arr2);

In this example, we use ‘__spreadArray’ to create a new array by first creating an empty array with ‘__spreadArray([], arr1)’, then adding ‘arr1’ to it, and finally adding ‘arr2’ to the result. The ‘__spreadArray’ function ensures that TypeScript understands that the first argument is an array and not undefined, which avoids the error that was produced earlier.

Now come to second solution.

2. By installing tslib library in our angular node module by following command.

npm install tslib@latest

Alternatively, if you are using a package manager other than npm, you can upgrade tslib using the appropriate command for your package manager.

Once you have upgraded tslib, you should no longer see this error message.

I hope you found this article informative and useful! If you know someone else who might be struggling with the same error, please share this article with them so they can benefit from this solution too. Thank you for reading!



Tuesday 21 February 2023

what is crawl request

 


A crawl request is a request made by a webmaster or website owner to a search engine's crawler to visit and crawl a specific web page or URL on their website.


Search engine crawlers (also known as spiders, bots or robots) are programs that scan the web, discovering and indexing new pages, and updating the search engine's index with new or updated content. When a website is crawled, the search engine's crawler visits the website and analyses the content of the pages to determine what the website is about and how relevant it is to specific search queries.


A crawl request can be useful for ensuring that a new or updated page on your website is indexed quickly by search engines. If you have made changes to a page that you want search engines to know about, you can submit a crawl request to the search engine so that it will visit the updated page and reindex it. This can help to ensure that the updated content is reflected in search results as quickly as possible.

It's worth noting that submitting a crawl request does not guarantee that the search engine will crawl your page immediately, but it can speed up the process. In general, search engines will crawl pages based on their own algorithms and schedule, so it's important to ensure that your website is optimized for search engines and that you regularly publish new and relevant content.

Sunday 21 June 2020

Create a component without spec file in Angular 9

How to Create a component without spec file in Angular 9?


In the angular 9 there are two ways to do this.

1. By using angular CLI command

Just use following commands to remove spec file for generate component

ng generate component componentname --spec=false;


2. or using Angular.json

just use following command

ng config schematics.@schematics/angular:component.spec false


it will create following section in angular.json

AdSense

The Ultimate Guide to Interceptors: Understanding Their Power and Functionality

  The Ultimate Guide to Interceptors: Understanding Their Power and Functionality An interceptor is a service that can intercept HTTP reques...

Follow