Different Types of Data Binding in Angular with Example

 There are mainly 4 types of data binding are available in Angular. Interpolation, Two-way data binding, event binding, and property binding. these bings are used to transfer the data from component to view and view to the component.

Different Types of Data Binding in Angular


Below is the list of Data BindingAngular.

  1. Interpolation 
  2. Two-way data binding 
  3. Event binding
  4. Property binding

What is Interpolation Data Binding in Angular?

  • Angular interpolation is used to display a component property in the respective HTML view template with double curly-braces "{{}}" syntax. 
  • We can display all kinds of property data into view e.g. date, arrays, list, number, string, modal data, or map.
  • Data binding consist of one-way data binding and two-way data binding. Interpolation is used for one-way data-binding from component to HTML elements. 
  • Interpolation moves data in one direction from our components to HTML elements.
Simple Syntax:

<div>{{ vendorName }}</div>
 
<div>{{ object.customerName }}</div>


Example with Component using inline HTML


import { ComponentOnInit } from '@angular/core';
 
@Component({
selector: 'app-ATG',
template: `
    <div>Welcome {{ vendorName }}! </div>
    <div>present Time {{ getTimeNow() }}!</div>`,
styleUrls: ['./ATG.component.css']
})
export class GreetComponent implements OnInit {
 
vendorNamestring = "All Tech Geeks";
 
getTimeNow(): string {
    return 'evening';
}


What is Property Data Binding Angular?

it helps to set the values for property and it is a one-way data-binding from component to HTML view template.

Simple HTML

<div>  
       Hello ATG.  
      </div>  
      <button class="btn btn-primary">Add Vendors</button> 


Property binding example

    
<div>  
        Hello ATG 2.
      </div>  
      <button class="btn btn-primary" [disabled]="allowNewATGServer">
Add Vendor</button> 
  

Component class for the above snippet


import { ComponentOnInit } from '@angular/core';  
  
@Component({  
  selector: 'app-ATG2',  
  templateUrl: './ATG2.component.html',  
  styleUrls: ['./ATG2.component.css']  
})  
export class CAT2Component implements OnInit {  
 allowNewATGServer false;  
  
  constructor() {  
    setTimeout(() =>{  
      this.allowNewATGServertrue;  
    }, 9000);  
  }  
  
  ngOnInit() {  
  }  
  



What is Event Data Bindingin Angular?

In Angular, it is nothing but passes the data from UI (HTML) to Component. event binding is used to handle the events raised by the client/ user/ HTML actions like the below events.
  • a button click, 
  • a mouse movement
  • keystrokes
  • key up
  • key down
  • mouse scroll e.g. 
When the DOM or client event happens at any element(e.g. click, key-down, key-up), it calls the specified method of that element in the particular component. 
Using Event Binding we can bind data from DOM to the component and hence we can use that data for further use.
below is the example for login in this example we have used the "ngSubmit" with onSubmit method   (ngSubmit)="onSubmit()"




<div class="card-body">
  <form [formGroup]="loginFB" (ngSubmit)="onSubmit()">
      <div class="form-group">
      <input type="text" formControlName="UserName" class="form-control" />
    </div>

     <div class="form-group">
      <input type="text" id="password" formControlName="Password" 
class="form-control"/>
    </div>          
     <div class="form-group">
         <button class="btn btn-lg btn-primary btn-block text-uppercase"
 type="submit">Login</button>
     </div>
  </form>
</div>


The Typescript code at component is below snippet

 
onSubmit() {

    this.loginModel.UserName = this.loginFB.get('UserName').value;
    this.loginModel.Password = this.loginFB.get('Password').value;
    // tslint:disable-next-line:no-debugger
    debugger;
    this.userService.login(this.loginModel)
    .subscribe(
        (resany=> {
          localStorage.setItem('token'res.token);
          // tslint:disable-next-line:no-debugger
          debugger;
          this.router.navigateByUrl('/home');
        },
        error => {
            this.erroMeg = 'error';
        });
      }




What is Two-Way Data Bindingin Angular?


this binding is very helpful when we are going to work both directional. In two-way data binding, automatic synchronization of data happens between the Model and the View with the help of the Component. due to that, any changes are reflected in both components. 

Example
If you make any changes in the Model, it will be reflected in the View and when you make any changes in View, it will be reflected in the Model



<div>Two-way Binding Vendor Example</div>    
   <input [(ngModel)]="vendorName" />    
<div> {{vendorName}} </div>  



Conclusion:

Data binding is the most powerful Element of Angular. because it gives us the data flow from view to component vise verse. we have discussed four types of Data binding in Angular helps to understand while you writing the angular code





logo
Read More »

What is Interceptor in Angular | Example

 Angular provides many built-in libraries to help scale out large applications. Interceptors are one of the built-in libraries for specifically handling HTTP requests and responses at a global app level.

it is a unique type of Angular Service that we can implement in Angular. HttpClient plays a major role. it modifies the app HTTP request globally before they send them back (Server).

What is Angular HTTP Interceptor

How to create the Interceptor in Angular

  • To implement an Interceptor in Angular, we need to create a class that’s injectable (Ex: AuthInterceptor )
  • The class should implement from the Interface HttpInterceptor.
  • The class should define an intercept method to correctly implement HttpInterceptor 
  • The intercept method takes the 2 main arguments, that are req and next, and returns an observable of type HttpEvent (Observable<HttpEvent<any>>)

Example Task below code going to check the Authorization and check the user is a valid user or not if the valid user then Authorize the Page if not redirect to the login page.



import { HttpInterceptorHttpRequestHttpHandlerHttpEvent } 
from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
import { Router } from '@angular/router';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

    constructor(private routerRouter) {

    }

    intercept(reqHttpRequest<any>, nextHttpHandler): Observable<HttpEvent<any>> {
        // tslint:disable-next-line:no-debugger
        debugger;
        if (localStorage.getItem('token') != null) {
            const clonedReq = req.clone({
                headers: req.headers.set('Authorization''Bearer ' + localStorage.getItem('token'))
            });
            return next.handle(clonedReq).pipe(
                tap(
                    succ => { },
                    err => {
                        if (err.status === 401) {
                            localStorage.removeItem('token');
                            this.router.navigateByUrl('/user/login');
                        } else if (err.status === 403) {
                            this.router.navigateByUrl('/forbidden');
                        }
                    }
                )
            );
        } else {
            return next.handle(req.clone());
        }
    }
}


The above code returns the Observable :

  • req is the request object (it is the type of HttpRequest).
  • next is the HTTP handler, (it is a type of HttpHandler).
To Achieve the Interceptor in Angular then we need to register it at Module as shown below



import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModuleHTTP_INTERCEPTORS } from '@angular/common/http';
import { AuthInterceptor } from './auth/auth.interceptor';

@NgModule({
  declarations: [
   ],
  imports: [    
    HttpClientModule
  ],
  providers: [UserService , { provide: HTTP_INTERCEPTORS
useClass: AuthInterceptor,
     multi: true }],
 })
export class AppModule { }








logo
Read More »

What is the difference between sessionStorage & localStorage

What is the difference between sessionStorage & localStorage

The sessionStorage and localStorage objects are the great objects on the client-side to store the data temporarily instead of cookies and they are two great tools for saving key-value pairs locally in the browser.

localStorage :

localStorage web objects in the browser store the information as long as the client/user does not delete them.

sessionStorage :

sessionStorage web objects in the browser store the information as long as the session goes. Usually, until the client/user closes the browser/tab.

Both objects have the same methods to perform the different operations like the below list.

  • getItem(key)
  • setItem(key, value)
  • removeItem(key)
  • clear
  • length
  • key(index)

Advantages of localStorage and sessionStorage

  • The data stored locally in the browser and can not read by any server
  • simple syntax
  • allows to store up to 10Mb data
  • Unlike cookies, web storage objects(sessionStorage & localStorage) are not sent to the server with each request.
  • Unlike cookies, the server can’t manipulate storage objects (sessionStorage & localStorage) via HTTP headers sent by the server. Everything’s done in JavaScript itself.

LocalStorage setItem example syntax :
in below syntax used local storage object and used 2 main methods. the methods are setItem and setItem. 

localStorage.setItem(key, 'testing');
undefined
localStorage.getItem(key);
"testing"


SessionStorage setItem example syntax :
in below syntax used local storage object and used 2 main methods. the methods are setItem and setItem. 

sessionStorage.setItem(key,'alltechgeeks')
undefined
sessionStorage.getItem(key)
"alltechgeeks"
Below syntax used to remove the item. we need to use a method like "removeItem" with the key.
below syntax tells to us as below steps
step 1: store a value in key
step 2: get the key-value
step 3: remove the key
step 4: check the key is available or not

sessionStorage.setItem(key,'alltechgeeks')
undefined
sessionStorage.getItem(key)
"alltechgeeks"
sessionStorage.removeItem(key)
undefined
sessionStorage.getItem(key)
null


logo
Read More »

Difference between abstract class and interface in C#

                                             Difference between abstract class and interface in C#


An abstract class is a half-defined base class and the interface is the contract between 2 parties(caller and callee). abstract is used to share something common in parent-child relations.

Abstract Class 

  • it is half defined base class
  • we can not create an instance to the abstract class
  • we are using abstract keyword


    Interface  Uses

    • It is a contract between caller and callee(2 parties)
    • we are not using abstract keyword


    logo
    Read More »

    C# Interface Tutorial with Example


    C# Interface Tutorial with Example


    The main point raises when we talk about Interface is a contract between 2 parties(caller and callee). and makes the alert to the developer.

    if any method name changes happen accidentally. it helps to implement impact analysis in case we change any method in which places it will impact.

    and it has different by-products like the below-mentioned list

    1. Multiple inheritances
    2. Signature
    3. Versioning
    4. Enforces rules
    5. Decoupling
    6. Abstraction (Show only what is necessary and hide unnecessary   methods)
    7. Standardization

    What is Contract in the real world?

    The contract is legally binding which two entities decided to follow on rules.

      if any one of them breaks the rule then that logic is not executed at the server.


    We have 2 types of contracts 

    • Implicit Contract

                    Here we directly using the reference in our project

    •  Explicit Contract

       Here we don't use the reference directly and going to decouple the code by using design patterns.

    Main Advantages using the Interface:

    • Use an Interface explicit contract where 2 parties are decoupled from each other.
    • Abstraction (Show only what is necessary and hide unnecessary  methods)
    • we can find the great Impact Analysis in the build time.
    • we have great change detection in the build time
    • Multiple inheritances happen when we need a new extension without disturbing the existed code.

    Some important Note:

    The interface should not be changed once it goes to production.


     


    logo
    Read More »

    SOLID Design Principles in C# Understand with Real-time Examples

    The Object-Oriented Design Principles are the core of OOP programming, but I have seen most of the Asp.net Developers chasing design patterns like Factory Design Patterns, Singleton pattern, Decorator pattern, Adapter Pattern or Observer pattern, and not putting enough attention on learning Object-oriented analysis and design.

    SOLID Design Principles in CSharp

    It's very important to learn the basics of Object-oriented programming like Abstraction, Encapsulation, Inheritance, Polymorphism. But, at the same time, it's equally important to know about object-oriented design principles. it will help you to create a modular and clean design, which would be easy to test in all scenarios, debugging, and maintain the code in the future.


    SOLID Design Principles

    There are five SOLID Design Principles as shown below list and OOD:

    1. Single Responsibility Principle (SRP)
    2. Open-Closed Principle (OCP)
    3. Liskov Substitution Principle (LSP)
    4. Interface Segregation Principle (ISP)
    5. Dependency Inversion Principle (DIP)
    6. DRY
    7. Delegation Principles (Don't repeat yourself)

    Advantages of SOLID Design Principles in C#

    The main advantage is helping to decouple the code. below are some advantages
    1. Maintainability
    2. Testability 
    3. Flexibility and Extensibility
    4. Easy to debugging the code
    5. Parallel Development

    Single Responsibility Principle (SRP)

    Clas should always handle the single or only one type of functionality or there should be one reason to change or modify the class and there should not be more than one reason to change the class.
    for example:
    I have the Vendor class then I have the chance to change the code when I get the changes in Vendor modification not on the Customer modification side.


    Open-Closed Principle (OCP)

    the name itself tells the meaning is Open for extension closed for modification.





    logo
    Read More »

    Lazy loading vs Eager loading in Singleton Design Pattern in C#

    Lazy loading vs Eager loading in Singleton Design Pattern in C#

    In this article, We are going to discuss the Lazy vs Eager loading in Singleton Design Pattern to Achieve Thread Safety in C# with a real-time example. Please read our previous content/article before proceeding to this article where we discussed the Thread Safe Singleton Design Pattern in C# with real-time examples. As part of this content, we are going to discuss the following main points.

    1. What is Non-Lazy or Eager Initialization 
    2. Understanding The C# Lazy Keyword
    3. Lazy or Deferred Loading Initialization?
    4. How to make the singleton instance thread-safe using both Eager loading and Lazy loading with Examples?

    What is Non-Lazy or Eager Initialization 

    We can enhance the previous singleton design patterns article to a non-lazy loading pattern and we can call it an eager loading pattern.
    It is simple and nothing but initialized the required object before it is accessed. which means we are going to create the object and keep it ready and use it when we need it.

    Note: CLR takes care of the thread-safety. 

    Below are the steps to achieve the eager loading.

    Step 1:  Change the syntax in the Singleton class to below which means create a new object.

    Step 2: change to readonly property.

    Step 3: Remove double-check locking, single check locking, and object initialization


    From : private static Singleton_Design_Pattern singletonInstance = null;
    To :   private static readonly Singleton_Design_Pattern singletonInstance = new Singleton_Design_Pattern();

    Previous Singleton.cs class file looks like below code

    using System;

    using System.Threading.Tasks;

    namespace ConsolePractice

    {

       public sealed class Singleton_Design_Pattern

        {

            private static int count =0;

            private static Singleton_Design_Pattern singletonInstance = null;

            private static readonly object objctlock = new object();

            public static Singleton_Design_Pattern GetNewInstance

            {

                get {

                    lock (objctlock)

                    {

                        if (singletonInstance == null)

                        {

                            singletonInstance = new Singleton_Design_Pattern();

                        }

     

                    }

                  

                    return singletonInstance;

                }

            }

     

            private Singleton_Design_Pattern()

            {

                count++;

                Console.WriteLine("object "+count);

            }

            public void getEmployee(string message)

            {

                Console.WriteLine(message);

            }

        }

    }


    New Singleton Class looks like below code.


    using System;

    using System.Threading.Tasks;

     

    namespace ConsolePractice

    {

       public sealed class Singleton_Design_Pattern

        {

            private static int count =0;

            private static readonly Singleton_Design_Pattern singletonInstance =                                           new   Singleton_Design_Pattern();

                   public static Singleton_Design_Pattern GetNewInstance

            {

                get

                {

     

                    return singletonInstance;

                }

            }

     

            private Singleton_Design_Pattern()

            {

                count++;

                Console.WriteLine("object "+count);

            }

            public void getEmployee(string message)

            {

                Console.WriteLine(message);

            }

        }

    }



    What are Lazy or Deferred Loading Initialization and  Lazy keyword?

    The lazy keyword was available in dot net framework 4.0 and above version. it provides support for lazy initialization. in order to make a property lazy, we need to pass the object type to this lazy keyword which is being lazily initialized.

    to achieve this use lambda expression as a delegate.

    Below is the code for lazy loading


    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

     

    namespace ConsolePractice

    {

       public sealed class Singleton_Design_Pattern

        {

            private static int count =0;

            private static readonly Lazy<Singleton_Design_Pattern>  singletonInstance =

                new Lazy<Singleton_Design_Pattern>(()=>new Singleton_Design_Pattern());

                   public static Singleton_Design_Pattern GetNewInstance

            {

                get

                {

     

                    return singletonInstance.Value;

                }

            }

     

            private Singleton_Design_Pattern()

            {

                count++;

                Console.WriteLine("object "+count);

            }

            public void getEmployee(string message)

            {

                Console.WriteLine(message);

            }

        }

    }

     
















    logo
    Read More »