Top ten Javascript tricks part 4

Throw an error when parameters required for function

const requireParam = () => {
thorw new Error('This parameter is required')
}

const sumNumbers = (val1 = requiredParam(), val2 = requiredParam()) => {
return val1 + val2
}

sumNumbers(4, 5)
//Result: 9

sumNumbers(4, null)
//Result: 4

sumNumbers(4)
//Result: Uncaught Error: This  paramter is required

sumNumbers(4, undefined)
//Result: Uncaught Error: This  paramter is required

ES2018 new method “finally”

fetch(https://google.com).then((response) => {
console.log(response);
}).catch((error) => {
console.log(error)
})  // es2018 finally
.finally(() => {
//your code here
})

ES5 getters and setters

const user = {
firstName: "John",
lastName: "Doe"
}

//fullname is a virtual field
get fullName(){
return this.firstName + '' + this.lastName
},

//validate age before saving
set age(value) {
if(isNaN(value)) throw Error('Age must be a number')
this._age = Number(value)
},

// get age(){
return this._age
}

console.log(user.fullName) // John Doe
user.firstName = "vignes"
console.log(user.fullName) // vignes Doe
user.age = '25'
console.log(user.age) // 25
user.age ="Invalid text" // Error: Age must be a number

Multiple conditions in an IF statement

const status = 'online';

// Classical approach
if(status === 'online' || status === 'away' || status === 'busy'){
console.log('Do Something');
}

// A better approach
if(['online', 'away', 'busy'].indexOf(status) ! === -1) {
console.log('Do Something')
}

// Check indexOf with ~ operator
if(~['online', 'away', 'busy'].indexOf(status)){
console.log('Do Something')
}

// Even Better, using includes method => Favourite
if(['online', 'away', 'busy'].includes(status)){
console.log('Do Something')
}

Type coercion in Js
Type Coercion is the conversion of one type of object to a new object of a different type with similar content. Tapestry frequently must coerce objects from one type to another

console.log(false === 0) // true
console.log(true + false) // 1
console.log('val' + 40 + 60) // val4060
console.log(40 + 6 + 'val') // 46val
console.log('8' + 1) // 81
console.log('10' - 2) // 8
console.log(6 * null) // 0

ES6 startsWith() and endsWith()

const image ='hill-mountain.png';
const validImage = image.endsWith('.png');
// result: true

const hillMountain = 'Hill Mountain';
const startsWith = hillMountain.startsWith('Hill');
// result: true

Array.from()

The Array.from() methods crates a new shallowed copied array instance from an array or iterable object.

// Array from a string
Array.from('foo') 
//Result: ['f', 'o', 'o']

//Array form a set
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// Result get unique value: ['foo', 'bar', 'baz'] 


//Array from a Map
const mapper = new Map([ ['1', 'a'], ['2', 'b'] ]);
Array.from(mapper.values())
// ['a', 'b']

Array.from(mapper.keys());
//['1' , '2']

Array form an Array-like object (arguments)
function f(){
return Array.from(arguments)
}

f(1,2,3) //result [1, 2, 3]

//Using an arrow function as the map function to manipulate the elements
Array.from([1,2,3], x => x + x) 
// result [2, 4 , 6]

entries() method

The entries() method returns a new Array Iterator object that contains the key/ value pairs for each index in the array

const arr = ['a', 'b', 'c']
const iterator = arr.entries()
console.log(iterator.next().value) 
// Result: Array [0, "a"]
console.log(iterator.next().value)
//Result: Array [1, 'b']

Array replacer by JSON.stringify()

const user = {
'username': 'helperscripter',
'email': 'help@helperscript.com',
'password': 'yourpassword'
}

const userString = JSON.stirngify(user, ['username', 'email']);
//result: 
{
'username': 'helperscripter',
'email': 'help@helperscript.com'
}

Javascript some() and Every() functions

const moneyHeist = [
{name : 'Denvar', age: '25'},
{name : 'Oslo', age: '40'},
{name : 'Tokyo', age: '17'}
]

moneyHeist.every(el => el.age > 18)
//return  false

moneyHiest.some(el => el.age < 18 )
//return true

I hope you all enjoy these methods and tricks. Thanks for reading. Please comment if it is useful.

< Javascript trick part 3

Top ten Javascript tricks part 3

Different ways to pass parameters to a setTimeout

const addNum = (a, b) => console.log(a + b); setTimeout(addNum, 1000, 2, 3) //result: 5 setTimeout(() => { addNum(2,3); },1000) //result: 5 setTimeout(addNum.bind(null, 2, 3), 1000); //result: 5

3 ways to get the Date and Time in milliseconds

new Date().getTime(); // 1576509862158 Date.now(); // 1576509862158 +new Date(); // 1576509862158

function() declaration in ES5 and ES6

// old way ES5
function tomAndJerry(){
}

// Es6
tomAndJerry() => {
}

Caching the array.length in the loop

let array = new Array(le9);

for(let i = 0; i < array.length; i++){
// this loop will calculate array length in each iteration
}

for(let i = 0; length =  array.length; i < array.length; i++){
// this loop will calculate array length only once
}

Different approaches to creating an HTML link

let myText = 'Click me please'

// usual way
`<a href="#">${myText}</a>`
// <a href="#">Click me please</a>

// Using link method
myText.link(#);
// <a href="#">Click me please</a>

Easily check the visibility of div or page

window.addEventListener('visiblitychange', ()=> {
// document => define any html element div, a, span
if(document.hidden){ 
console.log('div is hidden')
}else{
console.log('div is visible')
}
})

Check the data array or not? using isArray()

let array = [1,2,3,4]
let numb = 3

Array.isArray(array) // return true

Array.isArray(numb) // return false

Array.reduce()
It applies a function to each element in an array and reduces the array into a single element.

const arr = [5, 10, 15, 20, 25];

const result  = arr.reduce((total, currentValue) => {
console.log(currentValue); // 5 10 15 20 25
return total+currentValue;
});

console.log(result)
//result 75

How to verify that a given argument is a number

isNumber = (n) => {
return !isNaN(parseFloat(n)) isFinite(n);
}

isNumber(4) // true

isNumber(4.4) // true

isNumber('4') // false

Generate a random set of alphanumeric characters

// genreate random aplhanumeric
generateRandomAlphaNum = len =>{
var rdmString='';
for(; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
return rdmString.Substr(0, len);
}


generateRandomAlphaNum(5) // result blphj
generateRandomAlphaNum(11) // result: uug4th6ie2h
generateRandomAlphaNum(8) // result: rimbe38x

I hope this will help your developing skills. If any queries feel free in below comment section. Have a great day!.

< Javascript trick part 2 Javascript tirck part 4 >

Top Ten javascript tricks – part 2

Converting Object to Array – ES2017

// Converting Object => Array

const zoo = {
lion : 'animal',
peacock: 'bird'
}

//Keys
Object.keys(zoo)
// ['lion', 'parrot']

//values
Object.values(zoo)
// ['animal', 'bird']

//keys and values
Object.entries(zoo)
//[['lion','animal'], ['peacock','bird']]

Different ways to convert float to integer

Math.floor(5.95)
// 5

Math.ceil(5.15)
// 6

Math.round(5.4)
// 5

Math.round(5.5)
// 6

console.log(5.95 | 0); // quick way
//result: 5

Merging Object: Multiple objects into a single Object using the spread operator

const person= {name:'Jasim', gender:'Male'};
const tools ={computer:'Mac', editor:'VScode'};

const summary = {...person, ...tools};
*/
{
name: 'jasim',
gender:'Male',
computer:'Mac',
editor:'Vscode'
  }
/*

Make Console.log() output colorful and stylish in the browser console

console.log("%c I am red %c I am green", "color:red", "color:green" );
I am red I am green

Remove Character from String

let str ='Hello';

// remove first character
str.slice(1) // ello

// remove last character
string.substring(1,str.length -1)
// Hell

//remove substring from string
str.replace('ello', i)
// Hi

//remove character "LL" from "Hello" with split and join
str.split('l').join('')
// Heo

Add new element or push new element into an Array

let array = ['H', 'i'];

// add new element at last
array.push('!'); 
// ['H', 'i','!']

//add element at first
array.unShift('!')
// ['!','H', 'i']

3 ways to concat the multidimensional array

let nestedArray = [ [1, 2, 3], [4, 5], [6, 7,8]];

//using Array.flat() method
nestedArray.flat()
//result : [1, 2, 3, 4, 5, 6, 7, 8]

//usign concat and apply
[].concat.apply([], nestedArray)
//result : [1, 2, 3, 4, 5, 6, 7, 8]

//usign concat with ...spread operator
[].concat(...nestedArray);
//result : [1, 2, 3, 4, 5, 6, 7, 8]

Naming Conventional

//Camel case => mostly for variable declaration (camelCase)

<p id="camelCase>Hello!</p>
var camelCase;

//Pascal case (PascalCase)
class PascalCase{}

//hyphen html attribute declaration
<p class="main-paragraph">Hello1</p>

Array sort()

let array = [40, 2, 3, 45, 25, 100]

//Old way
array.sort(function(a, b){ return a-b});
// [2, 3, 25, 40, 45, 100]

//New Es6 way
array.sort((a,b) => a - b)
// [2, 3, 25, 40, 45, 100]

Change the color of cursor (caret) – CSS

input {
caret-color: auto
}

input{
caret-color: red
}
// text the color of below input caret cursor

I hope you enjoying this beautiful tricks in javascript. The third part of the javascript tricks in the next article.

< Part 1 javascript trick

Part 3 javascript trick >

How to read the excel file in angular with XSLX package

Here we add example code for fetching data from excel.

Add XLSX package to the angular project

npm install xlsx –save

read excel data in angular

Download demo Excel

app.component.ts

uploadExcel(e) {
  
  try{
  
  const fileName = e.target.files[0].name;
  
  import('xlsx').then(xlsx => {
    let workBook = null;
    let jsonData = null;
    const reader = new FileReader();
    // const file = ev.target.files[0];
    reader.onload = (event) => {
      const data = reader.result;
      workBook = xlsx.read(data, { type: 'binary' });
      jsonData = workBook.SheetNames.reduce((initial, name) => {
        const sheet = workBook.Sheets[name];
        initial[name] = xlsx.utils.sheet_to_json(sheet);
        return initial;
      }, {});
      this.products = jsonData[Object.keys(jsonData)[0]];
      console.log(this.products);

    };
    reader.readAsBinaryString(e.target.files[0]);
  });

}catch(e){
   console.log('error', e);
}

}

app.component.html

 <input type="file" (change)="uploadExcel($event)">

  <table >
    <thead>
      <tr>
        <th>#</th>
        <th>Product Identity</th>
        <th>Product Name</th>
        <th>Product Price</th>
        <th>Seller Name</th>
        <th>Total Count</th>
        <th>Status</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let product of products; let i = index">
      <td>{{i+1}}</td>
        <td>{{product.identity}}</td>
        <td>{{product.name}}</td>
        <td>{{product.price}}</td>
        <td>{{product.sellerName}}</td>
        <td>{{product.count}}</td>
        <td>{{product.status}}</td>
      </tr>
    </tbody>
  </table> 

app.component.css

table{
  width:75%;
  margin:20px auto;
}
table tr td, table tr{
  border-collapse: collapse;
  border:1px solid #ccc;
  font-size:14px;
}

I hope this will help. If any queries feel free to comment below.

Top ten Javascript tricks – part 1

Convert a string to an array of Characters using spread Syntax – ES6

// Split string uisng ES6 Spread
const angular  = 'angular';

//  old ways
const splicedAngualr = angular.split('');
// [ 'a', 'n', 'g', 'u' , 'l' , 'a' ,'r']

// new ES6 way
const splicedAngular = [...angular]
// [ 'a', 'n', 'g', 'u' , 'l' , 'a' ,'r']

Addition string (’10’) and number (5)

const str = '10';
const num = 5;

// This doesn't returnt the sum, its concatenated
str + num
// 105 (not correct)

//prepend string with "+" to calculate the sum
+str + num
// 15 (correct)

How to remove an Array Duplicates

const duplicates = [1, 2, 2, 4 , 5, 5, 6, 6];

const uniques = Array.from(new Set(duplicates));

// uniques [1, 2, 4, 5, 6]

3 ways to convert string to boolean

const isBool = 'Helperscript';

new Boolean(isBool) // true

Boolean(isBool) // true

!!isBool // true

How to check if NaN equals to NaN?

const item = NaN;

// this doesn't work
item === NaN; // false

//This works!
Object.is(item, NaN); // true

Two ways to repeat the strings

const str = 'J';

// 1. Repeat
str.repeat(3);

// 2. Fill
Array(3).fill(str).join('');

// result 'JJJJ'

Refactoring the ‘if’ condition

const isPerson = false;

//not correct
if(isPerson === false)

// correct
if(!isPerson)

Check if a string contains Substring

const word ='summer';

// old way
word.indexOf('sum') !=== -1 // true

// ES6 way
word.includes('sum');

Check the number is Negative or Positive

const num = -2;

// old ways
num === 0 ? num : (num > 0 ? 1 : -1) // -1

// ES6
Math.sign(num); // -1 if positive return 1 

The standard naming pattern for boolean variable

// Non standard
const person =  false;
const age = false;
cosnt dance = false

// Good standard
const isPerson =  true;
const hasAge = true;
cosnt canDance = true

I hope this will helpful for most beginners as well as to everyone. Thanks for reading. If you know any tricks comment below.

Javascript tricks part2 >

create angular CDK multi drag, drop and multi sorting

Why this post?

Angular CDK has beautiful drag, drop, and sort facilities, but we only able to move only one at a time. So, I give a solution to move with multiple selections of lists.

Angular CDK multi drag and drop with sorting video

Let see step by step from the package installation requirement.

npm i @angular/cdk

Step 1 – Next to import the needed module

import {DragDropModule} from ‘@angular/cdk/drag-drop’;

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {DragDropModule} from '@angular/cdk/drag-drop';
import { FormsModule } from '@angular/forms';
import { CommonModule } from '@angular/common';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,FormsModule,CommonModule, DragDropModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

I am using bootstrap jquery for Front End. If you don’t know how to import in angular. See this link.

Step 2 – Import some services like moveItemInArray, transferArrayItem form CDK drag-drop module.

import { CdkDragDrop, moveItemInArray, transferArrayItem } from ‘@angular/cdk/drag-drop’;

app.component.ts

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

import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';

declare var $: any;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  public tasks = [{
    title: 'All Tasks',
    taskList: [{
      id: 1,
      selected: false,
      name: 'Task 1'
    }, {
      id: 2,
      selected: false,
      name: 'Task 2'
    }, {
      id: 3,
      selected: false,
      name: 'Task 3'
    }, {
      id: 4,
      selected: false,
      name: 'Task 4'
    }, {
      id: 5,
      selected: false,
      name: 'Task 5'
    }, {
      id: 6,
      selected: false,
      name: 'Task 6'
    }, {
      id: 7,
      selected: false,
      name: 'Task 7'
    }, {
      id: 8,
      selected: false,
      name: 'Task 8'
    },
    {
      id: 9,
      selected: false,
      name: 'Task 9'
    }, {
      id: 10,
      selected: false,
      name: 'Task 10'
    },
    ]
  }, {
    title: 'Monday',
    taskList: []
  }, {
    title: 'Tuesday',
    taskList: []
  }, {
    title: 'Wednesday',
    taskList: []
  }, {
    title: 'Thursday',
    taskList: []
  }, {
    title: 'Friday',
    taskList: []
  }
  ];
  public ctrlPress = false;
  public dragData = [];
  public stored = [];
  public sortIndex = [];

  ondragging(event, item, data) {
    this.dragData = data;
    const a = this.stored.findIndex(x => x.id === item.id);

    if (a === -1) {
      item.selected = true;
      let idx = data.indexOf(item);
      this.sortIndex.push(idx);
      this.sortIndex.sort();
      this.stored = [];
      this.sortIndex.forEach(i => {
        data[i].selected = true;
        this.stored.push(data[i]);
      });

    } else {

    }



    $('.selected').addClass('dragging');

    $('.cdk-drag-placeholder').css({ 'opacity': '0 !important' });


  }


  drop(event: CdkDragDrop<any[]>, dropdata) {
    $('.selected').removeClass('dragging');
    $('.selected').css({ 'opacity': 1 });
    $('.cdk-drag-placeholder').css({ 'opacity': 1 });
    if (this.stored.length === 1) {
      if (event.previousContainer === event.container) {
        moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
      } else {
        transferArrayItem(event.previousContainer.data,
          event.container.data,
          event.previousIndex,
          event.currentIndex);
      }
      this.stored = [];
      event.container.data.forEach((d) => {
        d.isMultidragging = false;
        d.selected = false;
      });
    } else {
      const storedCloner = JSON.parse(JSON.stringify(this.stored));
      if (event.previousContainer === event.container) {
        let b = event.currentIndex;
        const clonerdata = Object.assign([], event.previousContainer.data);

        const extra = Math.max.apply(Math, this.sortIndex.map((o) => { return o; }));
        if (extra < b) {
          b = b + 1;
        }
        clonerdata.forEach((elem, i) => {
          if (elem.selected) {
            const b = dropdata.findIndex(x => x.id === elem.id);
            dropdata[b].id = 0;

          }
          if (clonerdata.length === (i + 1)) {
            storedCloner.slice(0).reverse().forEach((item, idx) => {
              dropdata.splice(b, 0, item);
              if (storedCloner.length === (idx + 1)) {
                setTimeout(() => {
                  dropdata.forEach((el, index) => {
                    if (el.id === 0) {
                      dropdata.splice(index, 1);
                    }
                  }, 1000);
                });

              }
            });
          }
        });


        this.stored = [];
        event.container.data.forEach((d, id) => {
          if (d.id === 0) {
            event.container.data.splice(id, 1);
          }

          d.isMultidragging = false;
          d.selected = false;
        });


      } else {
        if (this.stored.length > 0) {
          event.previousContainer.data.slice(0).reverse().forEach((item, idx) => {
            if (item.selected) {
              event.previousContainer.data.splice(event.previousContainer.data.indexOf(item), 1);

              event.container.data.splice(event.currentIndex, 0, item)
              event.container.data.forEach((d) => {
                // d.isMultidragging=false;
                d.selected = false;
              })

            }
          });
          this.stored = [];

        } else {

          transferArrayItem(event.previousContainer.data,
            event.container.data,
            event.previousIndex,
            event.currentIndex);
          event.container.data.forEach((d) => {
            d.isMultidragging = false;
            d.selected = false;
          });
          this.stored = [];

        }
      }

    }

    this.sortIndex = [];


  }

  onKeyDown(e, item, data) {
    this.ctrlPress = e.ctrlKey;
    if (e.ctrlKey) {
      const idx = data.indexOf(item);
      this.sortIndex.push(idx);

      this.stored = [];
      const result = [];
      const map = new Map();
      for (const item of this.sortIndex) {
        if (!map.has(item)) {
          map.set(item, true);    // set any value to Map
          result.push(item);
        }
      }
      this.sortIndex = result;
      this.sortIndex.forEach(i => {

        data[i].selected = true;
        this.stored.push(data[i]);

      });
    }

  }

}

The above code has all functions like
1. ondragging() // drag started
2. drop() // on drop the dragged data
3. onKeyDown() // selection of list

We have a task list in the above example for Monday to Friday to assign the task.

ondragging() function doing when dragging the unselected element its check and added to the already item selected to drag. So when dropped if any selected item there will also be dropped into the container.

drop() function – It helps to drop the task in one container and remove the task from the previous container.

onKeyDown() function – It helps to select an item or deselect an item from the task list.

Step 3 – Add HTML for the front end view

app.component.html

<div class="container-fluid mt-2">
  <div class="container" cdkDropListGroup>
    <div class="row d-flex justify-content-start">

      <div class="col-md-4 mb-3" *ngFor="let task of tasks; let i = index">
        <div class="card">
          <div class="header">
            <h6 class="p-2 bg-secondary text-white text-uppercase">{{task.title}}</h6>

          </div>
          <div class="card-body p-0" style="height:300px;overflow:auto" cdkDropList [cdkDropListData]="task.taskList"
            (cdkDropListDropped)="drop($event, task.taskList)">
            <ul class="list-group">

              <li class="list-group-item border" *ngFor="let t of task.taskList" cdkDrag
                (cdkDragStarted)="ondragging($event, t, task.taskList)" (click)="onKeyDown($event, t, task.taskList)"
                [ngClass]="{'border-primary':t.selected,'selected':t.selected}">{{t.name}}
                <div *cdkDragPreview>
                  <ul class="list-group">
                    <li class="list-group-item border" *ngFor="let s of stored" style="min-width:200px;">{{s.name}}</li>
                  </ul>
                </div>
              </li>
            </ul>
          </div>

        </div>

      </div>

    </div>

  </div>
</div>

Important to know the details of
1. cdkDropListGroup
2. cdkDropList
3. [cdkDropListData]
4. (cdkDropListDropped)
5. cdkDrag
6. (cdkDragStarted)

cdkDropListGroup => If you add to the top of the drag-drop containers. It says any drop list can able to accept the dragging data. If you want to some container will accept only form particular then you can use [cdkDropListConnectedTo] . Its an array you can push the reference in to drop list connected.

cdkDropList => It says that the container will accept the dragging data.

[cdkDropListData] => You will add task list data into this.

(cdkDropListDropped) => It is an event triggering when dropping initiated.

cdkDrag => Which says that the elements are draggable.

(cdkDragStarted) => It is an event triggering when drag started.

Step 4 – Add some CSS for better visibility.

app.component.css

.card-body::-webkit-scrollbar {
  width: 7px;
}
 
.card-body::-webkit-scrollbar-track {
  box-shadow: inset 0 0 10px transparent;
}
 
.card-body::-webkit-scrollbar-thumb {
  background-color: #c1c1c1;;
 border-radius:3.5px;
}
.selected.dragging{
  opacity:0.2;
}
.selected.dragging.cdk-drag-placeholder{
  opacity:0 !important;
}

That’s all. I hope this code will help you with something. Thanks for reading.

NOTE: If any queries feel free to ask in comment.

angular ng-filter-search to any component like table, list, div and etc

ng-filter-search

npm install ng-filter-search –save

Step1: Import FilterSearchModule to module.ts

https://www.npmjs.com/package/ng-filter-search

import {FilterSearchModule} from 'ng-filter-search';
@NgModule({
imports: [
    
    FilterSearchModule
  ]
})

step2: Import FilterSearchService to component.ts

import { Component } from '@angular/core';
import {FilterSearchService} from 'ng-filter-search';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public productList: any;
  // productList must be a type any.
  public cloner = [];
  // searchMap is defined to which key to filter
  public searchMap = ['name', 'price', 'sellerName', 'status'];
 
  constructor(private fs: FilterSearchService){
// dummy productList you can load from your api
    this.productList = [{
      id: 1,
      identity: 11012,
      name: 'Blue Headset',
      price: '$123',
      sellerName: 'Alibaba',
      count: 12,
      status: 'Sold Out'
    },
    {
      id: 2,
      identity: 31012,
      name: 'Red Shoe',
      price: '$143',
      sellerName: 'Amazon',
      count: 2,
      status: 'Available'
    },
    {
      id: 3,
      identity: 6423,
      name: 'Red Shoe',
      price: '$123',
      sellerName: 'FlipKart',
      count: 5,
      status: 'Available'
    },
    {
      id: 4,
      identity: 64123,
      name: 'Mi Phone',
      price: '$1123',
      sellerName: 'FlipKart',
      count: 11,
      status: 'Sold out'
    },
    {
      id: 5,
      identity: 86423,
      name: 'Redmi pro',
      price: '$223',
      sellerName: 'Alibaba',
      count: 9,
      status: 'Available'
    }];
    // this.cloner is important to copy your productList
    this.cloner = [...this.productList];
  }
 
  onSearchChange(sval: string): void {
    // Use filterSearch() function to filter the data
    this.productList =  this.fs.filterSearch(sval, this.cloner, this.searchMap);
}
}

HTML

Table Filter search

<input placeholder="SEARCH FILTER" (input)="onSearchChange($event.target.value)" />
 
<table>
    <thead>
      <tr>
        <th>#</th>
        <th>Product Identity</th>
        <th>Product Name</th>
        <th>Product Price</th>
        <th>Seller Name</th>
        <th>Total Count</th>
        <th>Status</th>
      </tr>
    </thead>
    <tbody>
    // productList is an array of an object from which we need to filter
      <tr *ngFor="let product of productList; let i = index">
      <td>{{i+1}}</td>
        <td>{{product.identity}}</td>
        <td>{{product.name}}</td>
        <td>{{product.price}}</td>
        <td>{{product.sellerName}}</td>
        <td>{{product.count}}</td>
        <td>{{product.status}}</td>
      </tr>
    </tbody>
  </table>

For list

<input placeholder="SEARCH FILTER" style="float:left" (input)="onSearchChange($event.target.value)" />
 
  <ul>
    <li *ngFor="let product of productList">{{product.name}}</li>
  </ul>

You can apply this filter for any search filter.

angular2 multi-select update data not working in an array

Hi! In this article, we learn something trick in angular. Sometimes angular 2 multi-select does not update after pushing the new data into the array.

Let’s have an example :
I had a dropdown list of country, I need to add a new country to the dropdown list.

this.dropdownList = [ { “id”: 1, “itemName”: “India” }, { “id”: 2, “itemName”: “Singapore” }, { “id”: 3, “itemName”: “Australia” }, ]

I need to add Canada to this list. So EveryOne did the same logic was to push data into an array using push() method in javascript. Like

this.dropdownList.push({id:4, itemName: ‘Canada’})

That’s fine. But sometimes this push method not update in your dropdown list. It’s not shown to your front end.

Let see a solution to such a situation. What I suggest just clone the old data and empty the current and reassign it to the list.

let cloner = […this.dropdownList]; this.dropdownList = []; // It may need or not need. this.dropdownList = cloner;

Example:
angular 2 multi-select: HTML5

angular 3 multi-select: .ts file

export class AppComponent { dropdownList = []; selectedItems = []; dropdownSettings = {}; ngOnInit() { this.dropdownList = [ { “id”: 1, “itemName”: “India” }, { “id”: 2, “itemName”: “Singapore” }, { “id”: 3, “itemName”: “Australia” }, ] this.dropdownSettings = { singleSelection: false, text: “Select Countries”, selectAllText: ‘Select All’, unSelectAllText: ‘UnSelect All’, enableSearchFilter: true, classes: “myclass custom-class” }; } onItemSelect(item: any) { console.log(item); console.log(this.selectedItems); } OnItemDeSelect(item: any) { console.log(item); console.log(this.selectedItems); } onSelectAll(items: any) { console.log(items); } onDeSelectAll(items: any) { console.log(items); } addCountry(){ this.dropdownList.push({id: 4, itemName: ‘Canada’}) } }

I hope this will helpful to you. Thank you for reading. If you like this please comment below. It will encourage me.

Udemy paid courses video free to download

20 Different courses Video fully free to download. Download and save the Udemy tutorial videos in your local. Maybe the videos will be deleted within a few days due to a lack of storage capacity.

paid Udemy courses free download

00)Angular 1.x

View folder to download

01) Html, css3, and bootstrap 4 courses

View folder to download

02) SEO full course free Udemy download

View folder to download

03) Netbeans

View folder to download

04) Excel for beginners

View folder to download

05) Game courses

View folder to download

06) Microsoft Azure course Udemy

View folder to download

Photoshop Tutorial free course Udemy video

View folder to download

Other new links

1.Angular Material Courses from Udemy

View folder to download

2. CSS, Jquery free Udemy courses

View folder to download

3. Kotlin for Android Development Udemy

View folder to download

4. Android 4.0 programming in Java Udemy

View folder to download

5. Learn python 3 beginners to Advance

View folder to download

6. Linux commands line basics

View folder to download

7. Photoshop best practical project Udemy course

View folder to download

8. Photoshop for web design beginners

View folder to download

9. Photoshop Tips and Tricks video

View folder to download

10. Boostrap Rapid web design

View folder to download

11. ios app development enterprise video free

View folder to download

12. Ethical hacking only for learning(no misuse)

View folder to download

13. The ethical hacking course only for learning(no misuse)

View folder to download

14. Best photoshop design courses on Udemy totally free

View folder to download

15. Unity 3D games courses tutorial

View folder to download

16. WordPress SEO – complete Yoast SEO tutorial download free

View folder to download

17. Photoshop depth in 100% worth video

View folder to download

18. How to succeed on fiver freelance

View folder to download

19. Maya 3D Animations & Visual Effects for Beginner

View folder to download

20. SEO best courses for ranking your websites

View folder to download