Tuesday, 29 June 2021

ng-template, ng-container and ng-content

 Difference between ng-template, ng-container and ng-content

1: <ng-template></ng-template>

As the name suggests the <ng-template> is a template element that Angular uses with structural directives ( *ngIf , *ngFor , [ngSwitch] and custom directives). These template elements only work in the presence of structural directives, which help us to define a template that doesn’t render anything by itself, but conditionally renders them to the DOM. It helps us create dynamic templates that can be customized and configured.

<div>
   <span *ngIf = "isavailable;then condition1 else condition2">
Condition is valid.
   </span>
   <ng-template #condition1>Condition is valid from template</ng-template>
   <ng-template #condition2>Condition is invalid from template</ng-template>
</div>

Is it possible to use two structural directives together in one single element?

No, if we try to do so, we will get the error “Uncaught Error: Template parse errors: Can’t have multiple template bindings on one element.”

So instead of doing this:

<div *ngIf="details" *ngFor="let info of details">
  {{ info.content }}
</div>

We may need to introduce an additional wrapper component, however, this can be avoided by using ng-container:

2) <ng-container></ng-container>

ng-container is an extremely simple directive that allows you to group elements in a template that doesn’t interfere with styles or layout because Angular doesn’t put it in the DOM

This is helpful if you don’t want any extra div on DOM, you can simply use ng-container. 

<ng-container *ngIf="details">
  <div *ngFor="let info of details">
    {{ info.content }}
  </div>
</ng-container>

The advantage here is that we no longer need any additional wrapper(div) elements.

3) <ng-content></ng-content>

ng-content is used to project content into Angular components. You use the <ng-content></ng-content> tag as a placeholder for that dynamic content, then when the template is parsed Angular will replace that placeholder tag with your content.

<app-child>
  <divChild Component Details </div>
</app-child>

If you check on your browser <div>Child Component Details</div> inside

<app-child></app-child> would not be visible. What if we want to show this content?
So this is where the ng-content directive comes into the picture. What we need to do is, just add “ng-content” inside the component template and it will find the content inside the directive tag and add it to that template at that particular place where we added the “ng-content” tag.


Reference: https://vibhas1892.medium.comhttps://www.educative.io/

Continue Reading →

Thursday, 24 June 2021

Why Multiple inheritance not allowed in C#

C# does not support multiple inheritance , because they reasoned that adding multiple inheritance added too much complexity and ambiguity in situations such as the "diamond problem", where it may be ambiguous as to which parent class a particular feature is inherited from if more than one parent class implements same feature.

The "diamond problem" is an ambiguity that arises when two classes B and C inherit from A, and class D inherits from both B and C. If there is a method in A that B and C have overridden, and D does not override it, then which version of the method does D inherit: that of B, or that of C?

It is called the "diamond problem" because of the shape of the class inheritance diagram in this situation. In this case, class A is at the top, both B and C separately beneath it, and D joins the two together at the bottom to form a diamond shape.

Continue Reading →

Wednesday, 23 June 2021

Beginner's Guide to ngrx and Angular

 What is RxJS?

RxJS is a JavaScript library for reactive programming that allows you to work with asynchronous or callback-based data streams.

NgRx stands for Angular Reactive Extensions. It is a state management system that is based on the Redux pattern.

RXJS + REDUX= NGRX

RXJS -> Observables

Redux is basically a global state mgmt. library taken from react. it is a storage facility that helps JavaScript applications to manage state.


So, now, we will see the overall concept of Redux and see how's it works. Here, we can see that we have a component, and when a user performs an action, it will change the state of the data within the application.

There are some main concepts of state in an angular application.

  1. Store
  2. Reducers
  3. State
  4. Actions
  5. Selectors
  6. Effects

States of an app in Redux are kept in the store. The states are updated using actions transported to pure functions called reducers. Reducers take in state and action as parameters and performs an immutable action on the state and returns a new state.

Store

A store is basically a JavaScript object that holds data we’ll be using in our application.
A simple store takes the following format:

const state = {
    persons: [
        {
            name: "Wisdom Ekpot",
            age: 10
        }, {
            name: "John Cat",
            age: 40
        },
        {
            name: "James John",
            age: 11
        }
    ],
    bookDescription: {
        name: "Name of book",
        author: "Wisdom Ekpot"
    }
}

Reducer

A reducer is a pure function that accepts two parameters - an action and the previous state with a type and optional data associated with the event. Pure means that the function always returns the same value for the same input. It generates a new state based on an action. 

Sample Reducer 

export function reducer(state = initialStateactionarticles.Actions):State {
    switch(action.type) {
        case 'ADD_ARTICLE':
            return { 
                articles: [...state.articles,action.payload]
            }
        default:
            return state;
    }
}

State

Theoretically, application state is the entire memory of the application. In simple terms, application state is composed of data received by API calls, user inputs, presentation UI state, application preferences, etc. A simple, concrete example of an application state would be a list of customers maintained in a CRM application.

Actions

An action is an instruction that you dispatch to the store, optionally with some metadata (payload). Based on the action type, the store decides which operations to execute. payload is an optional attribute that will be used by reducers to modify the state. 

When an action is dispatched, the reducer takes it and applies the payload, depending on the action type, and outputs the new state.

// Action interface
export interface Action {
    typestring,
    payload?: any
}

// Action with payload
dispatch({type: 'ADD_ARTICLE'payload: {link: 'github.com/philipszdavido'points:90}})

// Action without payload
dispatch({type:'LOAD_LINKS'})

Selectors: Selectors are pure functions used for obtaining slices of the store state.

Dispatcher: Dispatchers are simply an entry point for you to dispatch your action. In Ngrx, there is a dispatch method directly on the store.

How it Works

When an event is emitted, for example, a button is clicked, the action is sent to a reducer function to convert the old state into the new state:

type'DELETE_ITEM'payload123 }

Here, you can see that in action, Delete_Item is our action name and 123 is an action data.

References: https://stackabuse.com/,
https://betterprogramming.pub/,
https://dzone.com/,
https://www.youtube.com/

Continue Reading →

Wednesday, 2 June 2021

Deep and Shallow Copy in Javascript

 Shallow copy

Shallow copy is a bit-wise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

Deep copy

A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

Lets take an example

Shallow Copy: It makes a copy of the reference to X into Y. Think about it as a copy of X’s Address. So, the addresses of X and Y will be the same i.e. they will be pointing to the same memory location.

Deep copy: It makes a copy of all the members of X, allocates different memory location for Y and then assigns the copied members to Y to achieve deep copy. In this way, if X vanishes Y is still valid in the memory.

The correct term to use would be cloning, where you know that they both are totally the same, but yet different (i.e. stored as two different locations in the memory space).

Consider this example:

var employeeDetailsOriginal =
        {name: 'Manjula'age: 25Profession: 'Software Engineer'};

Let’s say you want to create a duplicate of this, so that even if you change the original values, you can always return to the original.

//Shallow copy!
var employeeDetailsDuplicate = employeeDetailsOriginal

If we change a value:

employeeDetailsDuplicate.name = 'NameChanged';

This statement will also change name from employeeDetailsOriginal, since we have a shallow copy, or a reference to var employeeDetailsOriginal. This means, you’re losing the original data as well.

But, creating a brand new variable by using the properties from the original employeeDetailsOriginal variable, you can create a deep copy.

//Deep copy!
var employeeDetailsDuplicate = { name: employeeDetailsOriginal.name,
    age: employeeDetailsOriginal.age
    Profession: employeeDetailsOriginal.Profession};

Now if you change employeeDetailsDuplicate.name, it will only affect employeeDetailsDuplicate and not employeeDetailsOriginal

Diagramatic example


Reference: https://medium.com/

Continue Reading →

Monday, 31 May 2021

package.json vs package-lock.json difference

 Package.json:

package.json is a file that contains information about your project (name, version, etc.) and it lists the packages that your project is dependent on.


So as you can see in the picture above after every dependency listed under package.json there's a number something like ^2.20.0 which is the version of that package but before the version, there is ^. So ^ (caret symbol) this little guy can be a total destroyer for your project.

^ sign before the version tells npm that if someone clones the project and runs npm install in the directory then install the latest minor version of the package in his node_modules.

So lets say I am having express with ^2.20.0 in package.json and then express team releases version 2.24.0 and now when someone clone my repo and runs npm install in that directory they will get the version 2.24.0 (You can also put ~ instead of ^ it will update to latest patch version)

However, this can be a huge issue if package developers break any of the functions on the minor version as it can make your application break down.

So npm later released a new file called package-lock.json to avoid such scenarios

package-lock.json:

package-lock.json will simply avoid this general behavior of installing updated minor version so when someone clones your repo and run npm install in their machine. NPM will look into package-lock.json and install exact versions of the package as the owner has installed so it will ignore the ^ and ~ from package.json.

Reference: https://medium.com/

Continue Reading →

Friday, 23 April 2021

Event Bubbling in JS

 The bubbling principle is simple.

When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.

Let’s say we have 3 nested elements FORM > DIV > P with a handler on each of them:

<!DOCTYPE html>
<html>
<!doctype html>
<body>
<style>
  body * {
    margin10px;
    border1px solid blue;
  }
</style>

<form onclick="alert('form')">FORM
  <div onclick="alert('div')">DIV
    <p onclick="alert('p')">P</p>
  </div>
</form>
</body>
</html>

Click here for demo. https://www.w3schools.com/

A click on the inner <p> first runs onclick:

On that <p>.

Then on the outer <div>.

Then on the outer <form>.

And so on upwards till the document object.

So if we click on <p>, then we’ll see 3 alerts: p → div → form.

The process is called “bubbling”, because events “bubble” from the inner element up through parents like a bubble in the water.

Stopping bubbling

A bubbling event goes from the target element straight up. Normally it goes upwards till <html>, and then to document object, and some events even reach window, calling all handlers on the path.

But any handler may decide that the event has been fully processed and stop the bubbling.

The method for it is event.stopPropagation().

For instance, here body.onclick doesn’t work if you click on <button>:

<body onclick="alert(`the bubbling doesn't reach here`)">
    <button onclick="event.stopPropagation()">Click me</button>
  </body>

Reference : https://javascript.info/

Continue Reading →

Wednesday, 21 April 2021

Change detection in Angular

 What is change detection?

The basic mechanism of the change detection is to perform checks against two states, one is the current state, the other is the new state. If one of this state is different of the other, then something has changed, meaning we need to update (or re-render) the view.

Change Detection means updating the view (DOM) when the data has changed.

How Change Detection Works

A change detection cycle can be split into two parts:

  • Developer updates the application model
  • Angular syncs the updated model in the view by re-rendering it

Let us take a more detailed look at this process:

  • Developer updates the data model, e.g. by updating a component binding
  • Angular detects the change
  • Change detection checks every component in the component tree from top to bottom to see if the corresponding model has changed
  • If there is a new value, it will update the component’s view (DOM)

The following GIF demonstrates this process in a simplified way:


Reference: https://www.mokkapps.de/




Continue Reading →

Friday, 15 January 2021

Angular 6 - Get current route and it's data

 How to get current route you're in and get's it's data, children and it's parent?

say if this is the route structure:

const routesRoutes = [
    {path: 'home'component: HomeComponentdata: {title: 'Home'}},
    {
      path: 'about'
      component: AboutComponent
      data: {title: 'About'},
      children: [
        {
          path: 'company',
          component: 'CompanyComponent',
          data: {title: 'Company'}
        },
        {
          path: 'Hr',
          component: 'HrComponent',
          data: {title: 'HR'}
        },
        ...
      ]
    },
    ...
  ]
 

Below is the solution code:

@Component({...})
export class CompanyComponent implements OnInit {

constructor(
  private routerRouter,
  private routeActivatedRoute
) {}

ngOnInit() {
this.pageTitle = this.route.snapshot.data['title'];

  // Parent:  about 
  this.route.parent.url.subscribe(url => console.log(url[0].path));

  // Current Path:  company 
  this.route.url.subscribe(url => console.log(url[0].path));

  // Data:  { title: 'Company' } 
  this.route.data.subscribe(data => console.log(data));

  // Siblings
  console.log(this.router.config);
}
}

Passing data between routes using State



Continue Reading →

Thursday, 14 January 2021

Subject with Example | Angular2+

 What is a Subject?

Subject is a type of Observable in RxJs Library in which we can send our data to other components or services.

While Observables are unicast by design. Subjects can multicast. Multicasting basically means that one Observable execution is shared among multiple subscribers.

A Subject is like an Observable but can multicast to many observers which means subject is at the same time an Observable and an Observer. Understanding of Subject

Important points of subjects:

  1. A Subject is a Special type of Observable that allows value to be multicasted to many Observers.
  2. Subject are like event emitters.
  3. No Initial Value allowed

subject =new Subject<datatype>();  

Lets create a basic demo for subject.

1- Create an angular application using below command: ng new subjectDemo   

2- Add three components in app/src using below command: 

ng g c Component1 
ng g c Component2 
ng g c Component3 

3- After that open Component1.component.html file and paste the below code.

<div style="background-color: aliceblue;" class="card">  
    <div class="card-body">  
      <h5 class="card-title">Component 1</h5>  
      <input name="comp1" #comp1 type="text" />  
      <button (click)="onSubmit(comp1)">Submit</button>  
      <p class="card-text">{{Component1Data}}</p>  
    </div>  
</div> 

4- After that open Component1.component.ts file and paste the below code.

import { Component } from '@angular/core';
import { DataSharingService } from '../dataService.service';

@Component({
  selector: 'app-component1',
  templateUrl: './component1.component.html',
  styleUrls: ['./component1.component.scss']
})
export class Component1Component{

  Component1Dataany = '';  
  
  constructor(private DataSharingDataSharingService) {  
    this.DataSharing.SharingData.subscribe((resany=> {  
      this.Component1Data = res;  
    })  
  }  
  
  onSubmit(data: { valueany; }) {  
    this.DataSharing.SharingData.next(data.value);  
  }  
}

5- After that open Component2.component.html file and paste the below code.

<div style="background-color:antiquewhite" class="card">  
    <div class="card-body">  
      <h5 class="card-title">Component 2</h5>  
      <input name="comp2" #comp2 type="text" />  
      <button (click)="onSubmit(comp2)">Submit</button>  
      <p class="card-text">{{Component2Data}}</p>  
    </div>  
</div> 

6- After that open Component2.component.ts file and paste the below code.

import { Component } from '@angular/core';
import { DataSharingService } from '../dataService.service';

@Component({
  selector: 'app-component2',
  templateUrl: './component2.component.html',
  styleUrls: ['./component2.component.scss']
})
export class Component2Component{

  Component2Dataany = '';  
  constructor(private DataSharingDataSharingService) {  
    this.DataSharing.SharingData.subscribe((resany=> {  
      this.Component2Data = res;  
    })  
  }  
  
  onSubmit(data: { valueany; }) {  
    this.DataSharing.SharingData.next(data.value);  
  }  
}

7- After that open Component3.component.html file and paste the below code.

<div style="background-color:burlywood" class="card">  
    <div class="card-body">  
      <h5 class="card-title">Component 3</h5>  
      <input name="comp3" #comp3 type="text" />  
      <button (click)="onSubmit(comp3)">Submit</button>  
      <p class="card-text">{{Component3Data}}</p>  
    </div>  
</div>

8- After that open Component3.component.ts file and paste the below code.

import { ComponentOnInit } from '@angular/core';
import { DataSharingService } from '../dataService.service';

@Component({
  selector: 'app-component3',
  templateUrl: './component3.component.html',
  styleUrls: ['./component3.component.scss']
})
export class Component3Component {
  Component3Dataany = '';  
  
  constructor(private DataSharingDataSharingService) {  
    this.DataSharing.SharingData.subscribe((resany=> {  
      this.Component3Data = res;  
    })
  }

  onSubmit(data: { valueany; }) {  
    this.DataSharing.SharingData.next(data.value);  
  } 
}

9- Now in the app.component.html file lets import the components selector using the following command.

<div style="text-align: center; font-size: x-large; font-family: monospace;">Example of Subject in RxJs</div>  
<div style="margin:10px" class="card-deck">  
  <app-component1></app-component1>  
  <app-component2></app-component2>  
  <app-component3></app-component3>  
</div> 

10- Now let's create a service so that one service can transfer data and use the stream of data.

import { Injectable } from '@angular/core';  
import { Subject } from 'rxjs';  
  
@Injectable({  
  providedIn: 'root'  
})  
export class DataSharingService {  
  
  SharingData = new Subject();  
  constructor() { }  
}

11- Now Run the application using ng serve command.


Change data in one component and submit. You will see the output in all component. 


Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives