How many ways to create Objects in JavaScript

 We can 5 ways to create objects in JavaScript.

Lets understand how to Create it...

Demo URL



'use strict';
Example 1

var fruit = {};
fruit.name = 'Mango';
fruit.color = 'Yellow';
console.log(`fruit name ${fruit.name} and color is ${fruit.color}`);

Example 2

var fruit2 = { name: 'Mango', color: 'Yellow' };
console.log(`fruit name ${fruit2.name} and color is ${fruit2.color}`);

function Fruit(name, color) {
  (this.name = name), (this.color = color);
}

Example 3

var fruit3 = new Fruit('Mango', 'Yellow');

Example 4

var fruit4 = new Fruit('Donut', 'Sprinkled Yellow');

console.log(`fruit name ${fruit3.name} and color is ${fruit3.color}`);
console.log(`fruit name ${fruit4.name} and color is ${fruit4.color}`);

console.log(`Check fruit3 proto ${Fruit.prototype === fruit3.__proto__}`);

// console.log(`Property descriptor
// ${JSON.stringify(Object.getOwnPropertyDescriptor(fruit,'name'))}`)

Example 5

var fruit5 = Object.create(Object.prototype, {
  name: {
    value: 'Mango',
    enumerable: true,
    writable: true,
    configurable: true,
  },

  color: {
    value: 'Yellow',
    enumerable: true,
    writable: true,
    configurable: true,
  },
});

console.log(`fruit name ${fruit5.name} and color is ${fruit5.color}`);
console.log(`Check fruit3 proto ${fruit.prototype === fruit5.__proto__}`);

var fruit6 = Object.create(Object.prototype, {
  name: {
    value: 'Mango',
    enumerable: true,
    writable: true,
    configurable: true,
  },

  color: {
    value: 'Yellow',
    enumerable: true,
    writable: false,
    configurable: true,
  },
});

fruit6.name = 'Sausages';
//compile error comment it later
//fruit6.color="Red";

for (var props in fruit6) {
  console.log(`${props} : ${fruit6.color}`);
}

console.log(
  `Fruit name ${fruit6.name} and color is ${
    fruit6.color
  } and proto ${JSON.stringify(fruit6.__proto__)}`
);

//Getter Setter

var fruit7 = {
  color: 'Yellow',
  get fruitcolor() {
    return this.color;
  },
  set fruitcolor(val) {
    this.color = val;
  },
};

console.log(`Fruit default color is ${fruit7.fruitcolor}`);

fruit7.fruitcolor = 'Yellow';

console.log(`Fruit changed color is ${fruit7.fruitcolor}`);

console.log(`Check Fruit3 proto ${Fruit.prototype === fruit3.__proto__}`);


What is the difference between Components and Directives?

 
Demo URL



@Components

@Directives

For register component we use @Component

meta-data annotation.


For register directives we use @Directive meta-data annotation.


Component is a directive which use shadow

DOM to create encapsulate visual behavior

called components. Components are typically

used to create Ul widgets.


Directives are used to add behavior to an existing DOM element.

Component is used to break up the application into smaller components.


Directive is used to design reusable components.



Only one component can be present per DOM element.


Many directive can be used in a per DOM element



Component is used to define pipes

You can't define Pipes in a directive.



@View decorator or templateurl template are

mandatory in the component.


Directives don't have a View.


What is the difference between constructor and ngOnInit? | Demo | Example



Demo URL




Constructor

ngOninit 

A constructor is not the concept of Angular. It is the concept of JavaScript's class.


ngOninit is the second stage of Angular

component lifecycle hook whenever is called

when angular is done which creating the

component.


Constructor is best place to add all dependencies


ngOninit function which guarantees you that the component has already been created.


Constructor is automatically called at the time of creating the object of the class.


Invoked by Angular when component is initialized


Used for Injecting dependencies


Actual business logic performed 



we should use constructor() to setup Dependency Injection

is a better place to write "actual work code" that we need to execute as soon as the class is instantiated.

PHP Fatal error: Array and string offset access syntax with curly braces is no longer supported in

 For making MailWatch work with Debian 11 and PHP 8, I had Fixed few code-file to avoid error :

PHP Fatal error: Array and string offset access syntax.

Sharing below changes for users using with PHP8., Hopeful to update in new version or users trying to use MailWatch with PHP8.
-Deepen.

Please change this 100% working

$c1 = $text[$i];

            if ($c1 >= "\xc0") { //Should be converted to UTF8, if it's not UTF8 already

                $c2 = $i+1 >= $max? "\x00" : $text[$i+1];

                $c3 = $i+2 >= $max? "\x00" : $text[$i+2];

                $c4 = $i+3 >= $max? "\x00" : $text[$i+3];


Solution




How to use Array.reduce with objects in Angular

Here Demo Filter Data




 

Demo Url


How to Share Local Storage | Session Storage between different domains | With Demo

 Here You can check how to share domain with Local Storage and Session Storage hare data between multiple domains (for example an auth token) can be somehow hard as we all know that all browser side data storage APIs (Localstorage, cookies etc.) are related to one specific domain.

    


Implementation:

1- Create a listener in the iframe that saves the data passed in localStorage

2- Create a listener in the iframe that sends the data back

3- Using postMessage, we invoke the iframe’s saving function from the parent

4- in whatever other domain we ask for the data from the iframe (using postMessage and listening for a response).

Iframe code

Listen to a message event, check the type of action (save or get) if save, it adds an item to LocalStorage, if get: return the data using postMessage

const domains = [
"https://www.domain1.com",
"https://www.domaine2.com"
]
window.addEventListener("message", messageHandler, false);function messageHandler(event) {
if (!domains.includes(event.origin))
return;
const { action, key, value } = event.data
if (action == 'save'){
window.localStorage.setItem(key, JSON.stringify(value))
} else if (action == 'get') {
event.source.postMessage({
action: 'returnData',
key,
JSON.parse(window.localStorage.getItem(key))
}, '*')
}
}

One of the other windows code will save a data

Uses postMessage to send a message event to the iframe.

const data = doSomeThingToGetData()
const iframe = iframe = document.getElementById('iframe-id')
iframe.contentWindow.postMessage({
action: 'save',
key: 'keyForData',
value: data
})

And now any time one of the windows wants to get this data

Send a message event and the listen to a message event that the iframe will send back.

const iframe = iframe = document.getElementById('iframe-id')
iframe.contentWindow.postMessage({
action: 'get',
key: 'keyForData'
})
window.addEventListener("message", messageHandler, false);function messageHandler(event) {
const { action, key, value } = event.data
if (action == 'returnData'){
useData(key, value)
}
}

Angular 13 Reactive Form Validation

 

Demo URL




Angular 13 Reactive Form Validation With Demo

 

Demo URL

Register Form Angular

How to add static text inside an input form


 


How to add static text inside an input form

  



What is Window: pagehide event in Javascript

 Here You can use Easy way pagehide.  The pagehide event is sent to a Window when the browser hides the current page in the process of presenting a different page from the session's history.

For example, when the user clicks the browser's Back button, the current page receives a pagehide event before the previous page is shown.


  1. A mobile user visits your page.
  2. The user then switches to a different app.
  3. Later, the user closes the browser from the app manager.

Examples

In this example, an event handler is established to watch for pagehide events and to perform special handling if the page is being persisted for possible reuse.

window.addEventListener("pagehide", event => {
  if (event.persisted) {
    /* the page isn't being discarded, so it can be reused later */
  }
}, false)

hookwebpackerror transform failed with 1 error error invalid version 15.2 15.3

Go to .browserslistrc and remove safari problem will be resolved 


last 1 Chrome version

last 1 Firefox version

last 2 Edge major versions

last 2 Safari major versions --- Remove this 

last 2 iOS major versions

Firefox ESR

not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line.


What is Array of Object in JavaScript?

 In This Article I will be show how to Array of Object Array  in JavaScript. 

Here Below Simple Object

{

 firstname:"Vijay",

lastname:"Chauhan",

type:"admin",

id:1

}

This Object represent a Registration There can be many types name  each object specific of Registration.




What is Destructuring in JavaScript

 The destructuring  is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

Demo URL



Syntax : let a, b, rest;

[a, b] = [10, 20];


console.log(a);

// expected output: 10


console.log(b);

// expected output: 20


[a, b, ...rest] = [10, 20, 30, 40, 50];


console.log(rest);

// expected output: Array [30,40,50]


What is literal in javascript

literal Syntax:

{foo:'Vijay'}

JavaScript Literals are constant values that can be assigned to the variables that are called literals or constants. JavaScript Literals are syntactic representations for different types of data like numeric, string, Boolean, array, etc data. ... The literal “Vijay” represents, the value Vijay for the variable name.

Javascript Class 2 Arrow Functions

 An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.





Javascript Class 1 Arrays

JavaScript Arrays sing an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...];.








What is JavaScript?

JavaScript is a scripting language that enables you to create dynamically updating content, control multimedia, animate images, and pretty much everything else. (Okay, not everything, but it is amazing what you can achieve with a few lines of JavaScript code.)




Best Practices Security of codes , Breaches Attack | SSR | Angular

 Security Code

1. Preventing cross-site scripting (XSS)

The injection of scripts into DOM elements is a very common occurrence to damage or steal the website data, such as:


1.Authentication details

2.Credentials

3.Payment data

4.Social Security numbers

5.Web tokens

2. HTTP-related Vulnerabilities

Cross-site request forgery (CSRF) and cross-site script inclusion are the most common HTTP vulnerabilities that can affect any Angular application, though Angular has created in-build assistants that prevent them from the client side. 

    Angular’s cross-site scripting security model

Sanitization and security contexts

Angular defines the following security contexts:


HTML is used when interpreting a value as HTML, for example, when binding to innerHtml.

Style is used when binding CSS into the style property.

URL is used for URL properties, such as <a href>.

Resource URL is a URL that is loaded and executed as code, for example, in <script src>.

Direct use of the DOM APIs and explicit sanitization calls

    Trusting safe values

To mark a value as trusted, inject DomSanitizer and call one of the following methods:

We need to make a service for BypassUrl

bypassSecurityTrustHtml

bypassSecurityTrustScript

bypassSecurityTrustStyle

bypassSecurityTrustUrl

bypassSecurityTrustResourceUrl

Server-side XSS protection

Avoid risky Angular APIs


The “Angular way” safeguards you from XSS

1.Use innerHTML with caution

2.Never use templates generated by concatenating user input

3.Never use native DOM APIs to interact with HTML elements

4.Avoid template engines on server-side templates

5.Scan your Angular project for components which introduce security vulnerabilities


SSR

1.Facilitate web crawlers through search engine optimization (SEO)

    2.Improve performance on mobile and low-powered devices

    3.Show the first page quickly with a first-contentful paint (FCP)

Data breaches Security

1. PASSWORD ATTACK

2. PHISHING AND SPEAR PHISHING 

3. EAVESDROP ATTACK

4. CROSS-SITE SCRIPTING ATTACK

Angular Template Syntax | Demo | Example

 More on template syntax

You might also be interested in the following:

  • Interpolation—learn how to use interpolation and expressions in HTML.
  • Template statements—respond to events in your templates.
  • Binding syntax—use binding to coordinate values in your application.
  • Property binding—set properties of target elements or directive @Input() decorators.
  • Attribute, class, and style bindings—set the value of attributes, classes, and styles.
  • Event binding—listen for events and your HTML.
  • Two-way binding—share data between a class and its template.
  • Built-in directives—listen to and modify the behavior and layout of HTML.
  • Template reference variables—use special variables to reference a DOM element within a template.
  • Inputs and Outputs—share data between the parent context and child directives or components
  • Template expression operators—learn about the pipe operator, |, and protect against null or undefined values in your HTML.
  • SVG in templates—dynamically generate interactive graphics

How to use splice Method In Angular

Splice method is changes the content of an Array  Which can help the Adding new element and also can removing odd Element.

Parameters of Details

Index: Index which of changing of the Array

HomMany: In Integer How many number in odds elements of array and removed if the 0 numbers in array can removed 

Ele: The Element can add of array which can add odd element 


The Syntax  Of Splice Method 

Array.splice(index, howmany, [ele1, ele2, ....eleN ])

Demo Url



 arr = ["orange", "mango", "banana", "sugar", "tea"];

SQL Server — Core Concepts with examples

  Data Definition Language (DDL) : CREATE , ALTER , DROP (tables, views, procedures, triggers). Data Manipulation Language (DML) : SELECT ,...

Best for you