Posts

How to export data to excel sheet with colors and style in angular.

 There are two most popular library for javascript to export data with excel sheet. 1) xlsx library 2) exceljs library If you would like to export simple data without changing its style then xlsx is perfact, but if you would like to change style before export then exceljs is perfect for JavaScript frameworks. Lets create an example with exceljs library to export data by changing style and colors for angular. Step 1: Install "exceljs" library                npm install exceljs Step 2: Install "file-saver" library to save excel file.                npm install file-saver Step 3: Import "exceljs" and "file-saver" library to your component. import * as ExcelJS from 'exceljs/dist/exceljs.min.js' ; import { saveAs } from 'file-saver' ; Step 4: Now create function in your component to export Data.   exportExcel ()   {     const workbook = new ExcelJS . Workbook ()...

How to create array of class type

    public variableName: ClassName[] = [];

How to install Redis as a window service

Step1: First of all Install Redis in your system. Step2: run Bellow command by going to Redis folder redis-server -- service-install   Step3: Now restart your system and Check Redis is working now.

How to change file with cmd on linux

step 1: Go to the directory where file exists then use bellow command to open file sudo vi filename step 2: Press i  to go to edit mode. now update your file step 3: Now press Esc then type  :wq!   to save and exit.

How to access shared folder from other PC on same network

 Go to run (win +r) type in \\ along with IP address of the sharing PC in this case e.g \\192.168.2.4 and press enter. You will get the folder that were shared

how to call angular function inside document.ready or setTimeout

use arrow function like bellow example myFunction() {      console.log('function called'); } Use like bellow $ ( document ). ready (() => { this . myFunction (); });

How to add common api url link to environment page in angular

step1) add url to your environment.ts.   export const environment = { production: false , apiUrl: 'www.localurl.com' }; step2) add same url to your environment.prod.ts export const environment = { production: true , apiUrl: 'www.productionurl.com' }; Now when you build for production like ng build --env=prod it will automatically use production url and when you build for local use like ng build it will use local url.

How to add push notification with ionic capacitor angular app

 Follow the tutorial from official Ionic website. https://capacitorjs.com/docs/guides/push-notifications-firebase 

How to add splash screen and app icon with ionic capacitor angular android app

step 1. first Install  npm install capacitor-resources -g  step 2. add bellow code to your package.json "scripts": { ... "resources": "capacitor-resources -p android,ios" } step 3. Now  Add your  icon.png (1024x1024 px)   and   splash.png (2732x2732 px)  in resources folder. Create new resources folder if its is not exists at the same location where package.json exists. step 4. Now run "npm run resources" command and that's it.  

how to create android apk with ionic capacitor angular

  First add android platform to your created ionic capacitor project step 1. ionic cap add android step 2. ionic cap copy step 3. ionic cap sync step 4. ionic capacitor build android step 4 will open android studio. now Go to  Build --> Build Bundle(s)/APK(s) --> Build APK(s) it will generate apk now you can install in your mobile and enjoy it.   Official IONIC document 

How to restrict your logged In page in angular (authentication guard)

 You can set authentication guard to restrict users which are not loggedin. 1) Service of auth guard    import { Injectable } from '@angular/core' ; import { Router , CanActivate , ActivatedRouteSnapshot , RouterStateSnapshot , UrlTree } from '@angular/router' ; import { CookieService } from 'ngx-cookie-service' ; @ Injectable ({ providedIn: 'root' }) export class AuthGuardService implements CanActivate { constructor ( private _router : Router , private _cookieService : CookieService ) { } userid = "" ; canActivate ( route : ActivatedRouteSnapshot , state : RouterStateSnapshot ): boolean | UrlTree { this . userid = this . _cookieService . get ( 'userid' ) if ( this . userid == "" ) { alert ( 'You are not allowed to view this page. You are redirected to login Page' ); this . _router . navigate ([ "login" ],{ queryParams: { retUrl: route . url } }); return false ; /...

How to notify about data update to other component.

   we can update about data changes to any component using bellow simple method 1) Service to publish and receive data import {Injectable} from '@angular/core'; import {Subject} from 'rxjs'; @Injectable({ providedIn: 'root' }) export class GlobalFooService { private fooSubject = new Subject<any>(); publishSomeData(data: any) { this.fooSubject.next(data); } getObservable(): Subject<any> { return this.fooSubject; } } 2) Data sending component @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'] }) export class HomePage { constructor(private globalFooService: GlobalFooService) { } onSomeButtonClick() { this.globalFooService.publishSomeData({ foo: 'bar' }); } } 3) Data receiving component @Component({ selector: 'app-root', templateUrl: 'app.component.htm...

what is observable in angular? promise vs observable.

Promise is active, whereas observable is lazy.  It means promise completes its next task till response comes. whereas observable do nothing and waits for the response. Promise is always asynchronous(start to run next code till response), whereas an Observable is default synchronous(don't run next code and wait for response) but you can make it asynchronous(you can forcefully make it asynchronous). Promise provide values only one time when you call the service. but Observable can continuously send value(notifications) on on fix time interval. for that you will have to set interval using "setInterval" function.     

how to delete selected objects from array by key value. javascript

//main array list arrayList = [{'id':1,'name':'salman',age:'22'},{'id':2,'name':'Adam',age:'21'},{'id':3,'name':'John',age:'23'}]; //list of object ids to be deleted idList [id:1,id:3]; //delete method idList.forEach(f => arrayList.splice(arrayList.findIndex(e => e.id === f.id),1));  console.log(arrayList); ----Output----  [{'id':2,'name':'Adam',age:'21'}];

how to save images with angular nodejs

 There are two ways to save images. 1) store image in database by converting it to binary format. 2) copy image in your project folder then save image path in table. ------- 1st way with front end angular------ pass uploaded file in "handleFileInput" function.  saveImage ( files :  FileList ) {    var   file : File  =  files . item ( 0 );    var   myReader : FileReader  =  new   FileReader ();    myReader . onloadend  = ( e )  =>  {      this . image  =  myReader . result ;   }    myReader . readAsDataURL ( file );    //convert to base64 ends } now you will get  binary format image in this.image variable. save this converted image directly to database through API. ------2nd way with api nodejs------ we can use "multer" to copy file in project folder. const   multer  =  require ( 'multer'...

How to filter objects from array javascript

 var products = [{"_id":1,"name":"product1 ","description":"good product"}, {"_id":2,"name":"product2 ","description":"good product"}, {"_id":3,"name":"product3 ","description":"good product"}, {"_id":4,"name":"product4 ","description":"good product"}, {"_id":5,"name":"product5 ","description":"good product"}]  var newArray = products.filter(function (el) {                 return el._id > 2;                }); -------Output------ [{"_id":3,"name":"product3 ","description":"good product"}, {"_id":4,"name":"product4 ","description":"good product"}, {"_id":5,"name":"product5 ","description":"good p...

important commands for angular CLI

1) Create Module :- ng g module ModuleName 2) Create Module with Routing :-  ng g module ModuleName --routing 3) Create Component :- ng g c ComponentName 4) Create Lazy Loading Module with Routing and Component :-  ng generate module ModuleName --route RouteLinkName --module app.module -->  RouteLinkName  is just a name   it can be anything whatever you wish.   

How to scroll page to Top on route change.

Add bellow code in app.component.ts file. this . router . events . subscribe (( evt ) => { if (!( evt instanceof NavigationEnd )) { return ; } window . scrollTo ( 0 , 0 ) }); app.component.ts import { Component } from '@angular/core' ; import { Router , NavigationEnd } from '@angular/router' ; @ Component ({ selector: 'app-root' , templateUrl: './app.component.html' , styleUrls: [ './app.component.css' ] }) export class AppComponent { title = 'AngularCrud' ; constructor ( private router : Router ) { } ngOnInit () { this . router . events . subscribe (( evt ) => { if (!( evt instanceof NavigationEnd )) { return ; } window . scrollTo ( 0 , 0 ) }); } }

how to create custom validator function

Step 1 :  Create the custom validator function   function  emailDomain(control: AbstractControl): { [key: string]: any } | null {    const  email: string = control.value;    const  domain = email.substring(email.lastIndexOf( '@' ) +  1 );    if  (email ===  ''  || domain.toLowerCase() ===  'gmail.com' ) {      return   null ;   }  else  {      return  {  'emailDomain' :  true  };   } } Step 2 :  Attach the custom validator function to the control that we want to validate email: [ '' , [ Validators .required,  emailDomain ]] Step 3 :  Display the validation error message <span  * ngIf = "employeeForm.get('email').errors.emailDomain" >   Email domian should be gmail.com </span>

How to update date in date picker??

Set Today's Date --> Most important thing while updating date in date picker is Date Format. Date format should be like yyyy-mm-dd . If it is not then date picker will not accept it. so first it should be convert to it using toISOString () method. <input type = "date" id = 'mydate' > <button onclick = " setcurrentdate ()" > Set Today's Date </button> <script> function setcurrentdate () { var date = new Date (); var date1 = date . toISOString (). substring ( 0 , 10 ) document . getElementById ( "mydate" ). value = date1 ; } </script>