Wednesday 26 February 2020

Conditionally add class using ngClass angular

AngularngClass

In this article we will be discussing about adding css class dynamically using angular [ngClass]. One of my previous articles I wrote about different ways of adding class dynamically.

Let us check what are the different ways we can add a class using ngClass.

1. Add single class
2. Add multiple class
3. Multiple conditions
4. Using shared or common service

Conditionally add class using Angular - 5 methods
Conditionally add class to an element on click - angular

1. Add single class



<p [ngClass]="{'active-class': status === 'read'}">Demo text</p>

Here class will get added if the conditions is true. Same you can add in a method and use as well.


<!--boolean -->
<p [ngClass]="{'active-class': isRead}">Demo text</p>

<!--using method -->
<p [ngClass]="{'active-class': isStatus()}">Demo text</p>


// example
public isRead: boolean = true;

public isStatus(): boolean {
    return true;
}

2. Add multiple classes


Similar way you can add multiple classes as well, check below examples.


<p [ngClass]="{'active-class1, active-class2': isStatus()}">Demo text</p>

3. Multiple conditions


Here we will be adding multiple classes using different conditions


<p [ngClass]="{'active-class1': status === 'read', 'read-class': isStatus()}">
  Demo text</p>

4. Using shared or common service


Create a shared service or a common service and declare your Boolean variable there. For example


<p [ngClass]="{'active-class1': commonService.readonlyStatus}">
  Demo text</p>

Simple service file


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

@Injectable({
  providedIn: 'root'
})
export class CommonService {

  public readonlyStatus: boolean;

  constructor() {
  }
}

Now import this service in your components where ever it is required and use this condition as below.


constructor(public commonService: CommonService) {
    //
  }

  public setValue(): void {
    this.commonService.readonlyStatus = true; // or false
  }

Advantage of using like this way, you can reset the variable in any component by importing this service file.

In this article we have discussed about adding class dynamically using angular ngClasss

Related Info

1. How to solve JavaScript heap out of memory issue in Angular project

2. Truncate file name without hiding the extension using Angular Pipe.

3. How to create and use shared module in angular application.

Friday 21 February 2020

Truncate file name without hiding the extension using Angular Pipe

AngularPipeTruncate

In this article we are going to discuss about truncating the file name with out hiding its extension. We can truncate file name only using CSS, but in this case, it will truncate extension as well. Check css example first for "angular-training.pdf"

Css


.truncateClass {
    display: inline-block;
    width: 30px; // your width
    white-space: nowrap;
    overflow: hidden !important;
    text-overflow: ellipsis;
}

Example result: angular...

In the above example it is truncating all the file name including the extension. It is not user friendly; user should know the file extension without hovering or clicking on the file. We can achieve this by using a simple angular pipe.

Example results


angular-[...].pdf

Truncate pipe


import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'truncate'
})

export class TruncateName implements PipeTransform{
  transform(name: string): string {
    const ext: string =
      name.substring(name.lastIndexOf('.') + 1, name.length).toLowerCase();
    let newName: string = name.replace('.' + ext, '');
    if (name.length <= 8) {
      // if file name length is less than 8 do not format
      // return same name
      return name;
    }
    newName = newName.substring(0, 8) + (name.length > 8 ? '[...]' : '');
    return newName + '.' + ext;
  }
}

Usage


this.fileName = 'angular-training.pdf';

<p title="{{fileName}}">{{fileName | truncate}}</p>

Result


angular-[...].pdf

Here we have created a simple pipe. You can use this pipe anywhere in your angular application. It will truncate the file name without hiding the extension. You can update […] this to (…) or any other way you want. As we added a title user can hover and see the full file name as well.

In this article we have discussed about creating a simple truncate pipe to truncate the file name without hiding its extension.

Related Info

1. How to solve JavaScript heap out of memory issue in Angular project

2. How to create an Angular application from scratch with simple steps.

3. How to create and use shared module in angular application.

Sunday 16 February 2020

Remove duplicate by using one line of code – JavaScript

JavaScriptES6Set

There are many different ways to remove duplicates. Here we will be using JavaScript ES6 feature, see below example.

Sample list


let list = [1,2,2,3,4,5];

Now we need to remove duplicates.


new Set(list);

We have used JavaScript Set operator.

See the result

But we need in array format, for that we can use JavaScript spread operator.


[...new Set(list)]

See the result now

Here we have discussed about removing duplicates using JavaScript ES6 feature.

Related Info

1. How to prevent modifying an Object – JavaScript.

2. How to solve JavaScript heap out of memory issue in Angular project.

3. How to rename key of an Object.

Saturday 15 February 2020

How to prevent modifying an Object – JavaScript

JavaScriptObjectFreezeSeal

In this article we are going to discuss about some JavaScript cool features which can prevent Object from modifying, adding a new property etc.

1. Freeze JavaScript Object
2. Seal JavaScript Object

Sample Object


const myObject = {
      name: 'Prashobh',
      status: 'JavaScript Developer'
    }

1. Freeze JavaScript Object

Here we are freezing the object that means you wont be able to modify or add a new property.


const myObject = {
      name: 'Prashobh',
      status: 'JavaScript Developer'
    }

Object.freeze(myObject);

Now try to modify the value.


myObject.name = 'another name';

You will be getting below console error.


Cannot assign to read only property 'name' of object '[object Object]'

Now try to add new property.


myObject['country'] = 'USA';


Cannot add property country, object is not extensible

Important note: You should run this in strict mode, use: 'strict'

2. Seal JavaScript Object

In this scenario you can modify the values but wont be able to add new properties. For example,


const myObject = {
      name: 'Prashobh',
      status: 'JavaScript Developer'
    }

Object.seal(myObject);

This way you will be able to update the values. For example you can do myObject.name = 'another name';. Now try to add new property.


myObject['country'] = 'USA';


Cannot add property country, object is not extensible

You cannot delete the property as well.

You can use below method to identify whether the Object is freezed or sealed. It will return true or false


Object.isFrozen(myObject).

Object.isSealed(myObject).

Object.isExtensible(myObject).

In this article we have discussed about Freezing and sealing a JavaScript Objects.

Related Info

1. How to solve JavaScript heap out of memory issue in Angular project.

2. How to rename key of an Object.

3. Remove duplicate by using one line of code – JavaScript

Friday 14 February 2020

How to create and use shared module in angular application

AngularShared moduleLazy loading

In this article we are going to discuss about creating a shared module and using it in an Angular application. If your project is big and you have lot of modules, and components are shared across the module then you need a shared module.

Take an example of having 10 modules in an Angular application, and you need to use many components across the modules. In this scenario it is not a good practise to import all components in all module or in app module. Instead of that create a shared module and import this in app module.

If you are using lazy module routing and shared module, then no need to import any module in app.module instead use shared module. You can have more than one shared module as well as per your requirement. This way you can improve the performance as well also it is will help you to prevent getting JavaScript heap memory issues.

Lazy loaded routing example


import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';

const routes: Routes = [
  {
    path: 'module-one',
    loadChildren: () => import('./sample-one/sample-one.module')
        .then(m => m.SampleOneModule)
  },
  {
    path: 'module-two',
    loadChildren: () => import('./sample-two/sample-two.module')
        .then(m => m.SampleTwoModule)
  }
];

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



Here make sure to add childRoot for lazy loaded modules and forRoot for appmodule.

App module


imports: [RouterModule.forRoot(routes)],

Child module


imports: [RouterModule.childRoot(routes)],

Now let us create two modules and one shared module.


import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SampleOneComponent } from './sample-one.component';
import {SampleOneRoutingModule} from './sample-one-routing.module';

@NgModule({
  declarations: [SampleOneComponent],
  imports: [
    CommonModule,
    SampleOneRoutingModule
  ],
  providers: []
})
export class SampleOneModule { }




import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import {SampleOneComponent} from '../sample-one/sample-one.component';


@NgModule({
  declarations: [SampleOneComponent],
  imports: [
    CommonModule
  ]
})
export class SampleTwoModule { }



Import the components which are required for the modules and if you feel some components should be reused across these modules then keep those in the shared module. And import this shared module in the appmodule.

Shared module example


import {ModuleWithProviders, NgModule} from '@angular/core';
import { CommonModule } from '@angular/common';
import {SharedComponentComponent} from './components/shared-component/shared-component.component';

@NgModule({
  declarations: [SharedComponentComponent],
  imports: [
    CommonModule
  ],
  exports: [SharedComponentComponent]
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: []
    };
  }
}



Here we are exporting our components, similar way you can add pipe, service etc.

Import shared module.


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {SharedModule} from './shared/shared.module';

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


Instead of importing all components every where we can create one or more shared module and manage the application easily. This will help us to improve the performance as well as the code visibility. In the above example I have added in the appmodule so that all shared components can use across the modules. Please find the screenshot of folder structure below.

In this article we have discussed about creating a shared module and using it in Angular application.

Related Info

1. How to solve JavaScript heap out of memory issue in Angular project

2. How to create an Angular application from scratch with simple steps.

Sunday 9 February 2020

How to solve JavaScript heap out of memory issue in Angular project

AngularHeap Memmory issueJavaScript

In this article we are going to discuss about JavaScript heap out memory issue which used to happen in Angular project. This issue you might have faced while running a project or building a project or deploying from Jenkin. This issue generally will happen if your project is really big or wrongly designed. However, we have solutions to address this issue. I am going to discuss about the solutions which I found in my experience. Before explaining those let us check some temporary solutions to over come this. To fix real issues you may required time, so use below thing for time being.

Temporary solutions to run the application

Once I faced this issue in one of my application, first I tried to build the application using below command instead of ng build.


ng node --max_old_space_size=4096 && ng build --prod

Here I have added max old space. But after some time again I faced the same issue, I end up with increasing the max old space size.


ng node --max_old_space_size=8192 && ng build --prod

This time even ng serve stopped working and started showing JavaScript heap out memory issue. I have forced to change ng serve as well.


node --max_old_space_size=8048 ./node_modules/@angular/cli/bin/ng serve

More info


node --max-old-space-size=1024

node --max-old-space-size=2048

node --max-old-space-size=3072

node --max-old-space-size=4096

node --max-old-space-size=5120

node --max-old-space-size=6144

node --max-old-space-size=7168

node --max-old-space-size=8192

Since It is going worse, the next thing was disabling AOT build, for that I have used below code.


ng build --prod --aot=false --build-optimizer=false

This is not at all a suggested way because we are disabling one of the angular features. As I said above all are the temporary solutions. Next thing I have done is that rechecking my application design, module import etc. Below are my findings and finally I solved JavaScript heap out of memory issue.

Proper module import and correct design for module.

First thing I have done is that cross checked all modules. I had around 10 modules in my application. I have created a shared module and moved all reusable components into that module. And imported shared module in other modules where ever it is applicable.

I am already using lazy routing module for my application, and hence removed all module import (Module which are created by me) from app module. Then checked all module import and cleaned up which are not required. After above changes itself you can see the difference. But I still started analysing more and found below issue as well.

Cross check stylesheet import

I have used scss file in my application. I have cross checked all SCSS and find out that lot of files were imported multiple times. Moved all common CSS to a single file (may be more than one, depends on your code) and imported only where it is applicable. Also stopped importing variable CSS file every where and instead imported only required places. Basically, I have rearranged my CSS file in a better way and made sure CSS files are not duplicated.

External libraries

Please be extra care full while selecting external libraries. Most of the libraries are not designed in Angular way. In my case I was using lodash and underscore, I have removed underscore first. As JavaScript ES6 has lot of features so we don't need many of these kinds of libraries. I have removed lodash as well and started using ES6 feature directly. My personal suggestion is that try to avoid using external libraries as much as possible. If you still want to use, for example lodash then wisely import. Don’t do complete file import everywhere.

Clean up unused import from component

This is last thing I have done, checked all components and removed unused import.

Conclusion

If your project is very big, plan design properly, use module wisely. Architect your application such a way that modules are configured properly. Split your application with different logistical modules and make sure all are imported properly. You can have more shared modules depends on your project. I will be sharing the design and folder structure of a complex angular application in my next article.

In this article we have discussed about, how to solve JavaScript heap memory issue in an Angular application also about the temporary solutions to over come this issue. Above all are written from my experience, if you know more and better solutions please comment it. It will be use full for others.

Related Info

1. Date filtering and formatting using pipe in Angular

2. Conditionally add class to an element on click - Angular

3. Conditionally add class using Angular - 5 methods

4. How to create an Angular application from scratch with simple steps.

Saturday 8 February 2020

How to create an Angular application from scratch with simple steps.

AngularApplication from scratch

In this article we are going to discuss about creating an angular application from scratch with simple steps.

Install node

Check you have installed node already else install node. To check which node version is installed, run below command in cmd(command prompt).


node –version

OR


node –v

Now we are ready to start our angular application.

Install angular/cli globally

Now install angular/cli globally. Create a folder and give any name, open cmd from same path. Run below command.


npm install -g @angular/cli 

Above command will install angular latest version. If you want any specific version, please use like below.


npm install -g @angular/cli@8.0.0

In above case it will install angular 8.0.0

We are done with angular cli, now let us create our angular project.

Create new angular project

Now we are ready with all prerequisites. Run below command to create angular project.


ng new angular-makeiteasy

While running above command, you will get below questions with respect to routing and style sheet.

Would like to add angular routing ?

If yes type "Y"

Which stylesheet format do you like to use ?

You can use down arrow and select the type of stylesheet format. In this example I selected SCSS.

Now check your folder which is created by running above command. Angular has taken care all of the files which you need to build an angular application. Check below image to see what are the file which got added automatically.

Do npm install, so that all package versions are installed properly. Now run ng serve and check your application in the path http://localhost:4200.


ng serve

If you don’t want to reload your application in browser on each code change, then use below command instead of above.


ng serve --live-reload=false

Below is the folder structure of our simple angular application.

Now create your first component by running below code.


ng g c example-component

Our first component is ready now. Do experiment yourself by adding more components, services etc. To create service file use below command.


ng g service example-service

In this article we have discussed about creating an angular application from scratch with simple example steps.

Related Info

1. File/image upload and send data to backend - Angular

2. Show preview image while uploading - Angular

3. Date filtering and formatting using pipe in Angular

4. Conditionally add class to an element on click - Angular

5. Conditionally add class using Angular - 5 methods

Wednesday 5 February 2020

How to rename key of an Object

JavaScriptRename KeyObject

In this article we are going to discuss about how to rename a key. Let us take an example of a simple object first.


let sampleObj = {
    "name": "Angular",
    "version": "8"
};

for (const k in sampleObj) {
    if (k === "name") {
        sampleObj["newKeyName"] = sampleObj[k];
        delete sampleObj[k];
    }
}

Here we deleted the key and added new one with out changing its value. End result is equal to rename the key.

Here we checked directly key === "name", you can add your own conditions. (indexOf(k), etc) according to your requirements.

Output

Now check with another example.


let data = [{
    "name": "Angular",
    "version": "8"
}, {
    "name": "React",
    "version": "6"
}, {
    "name": "Backbone",
    "version": "7"
}];

data.forEach((obj) => {
    for (const k in obj) {
        if (k === "name") {
            obj["newKeyname"] = obj[k];
            delete obj[k]
        }
    }
})



Here we are looping over array of object and renaming the key.

In this article we have discussed about how to rename key of an object.

Related Info

1. File/image upload and send data to backend - Angular

2. Show preview image while uploading - Angular