Angular – Routing

In this tutorial we will learn about Angular Routing, Angular Routing is one of the important functionality in angular, it makes navigation faster.

Routing is a component in angular which is used for navigation in the application to navigate from one view to the other.

Steps to implement routing in your angular application

Step 1: add base tag

  <base href="/">

Step 2: create or there already exist a routing module

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
  
const routes: Routes = [];
  
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

2 most important things to note here:

  1. create a routes constant array
  2. In the imports add the RouterModule.forRoot(routes)

Step 3: In the src/app/app.module.ts add import

import { AppRoutingModule } from './app-routing.module';

and add it in the Module imports as well

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
  })

Step 4: The router-outlet tag in app.component.html

<router-outlet></router-outlet>

The < router-outlet > tells the router where to display routed views.

The RouterOutlet is one of the router directives that became available to the AppComponent because AppModule imports AppRoutingModule which exported RouterModule.

Step 5: Add the anchor tags with routerLink and routerLinkActive directives to make the routing functional. Add this anchor tags in the page from where you want to access any other view.

<a routerLink=”/contact-form”></a>

Lets Understand with an Example

In this example we will be able to Add routes and open a contact form :

  1. ON – click of a button &
  2. ON – accessing the link directly in browser
angular-routing-on-click-of-a-button

Step 1: Lets create a component called contact component

 >ng g c contact
create-component-contact

In contact.component.html file add the below html for creating a simple contact form

<p>
contact works!
</p>

<div class="col-lg-4" >
<form [formGroup]="contactForm" (ngSubmit)="onSubmit()" class="form-horizontal">
  <h3 class="panel-title">Contact Form</h3>
  <div class="form-group">
    <label>Name</label>
    <input id="name" formControlName="name" type="text" class="form-control">
  </div>
  <div class="form-group">
    <label>Email</label>
    <input id="email" formControlName="email" type="text" class="form-control">
  </div>
  <div>
    <button type="submit" class="btn-primary">Submit</button>
  </div>
</form>
</div>

Step 2: create a constant of path in AppRoutingModule & also import the ContactComponent

Below is the code of AppRoutingModule

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ContactComponent } from './contact/contact.component';
  
const routes: Routes = [
  {
    path : 'contact-form', component : ContactComponent
  }
];
  
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Step 3: add anchor tag in app.component.html to call the contact form page

add the below html block in app.component.html page, you can add it anywhere in this file.

<div style="text-align: center">
    <button><a routerLink="contact-form" >Click to open form</a></button>
</div>
<hr>

Step 4: OUTPUT view of the page

Open url localhost:4200 , you will see this page below

angular-routing-on-click-of-a-button-executed

Now, Click on the button “Click to open form” as shown in the above snapshot, Or directly open the url “localhost:4200/contact-form” this will open the contact form page as shown below in the snapshot.

angular-routing-from-the-url

Summary

You are now good to go with Routing in angular, here we created a simple contact form page which we called on click of a button. Benefit of using angular routing is that it makes the navigation faster, simpler within the application in between different views or pages without refreshing the entire page.
Hope you liked it!


Angular Installation steps and create First angular app

Steps – Very simple to follow

1. Install Nodejs

Node.js provides the node package manager which manages the dependencies to run an angular Project. Node.js serves as the run time environment to run javascript based frameworks and applications.

GOTO Node js official link to download and install Node.js https://nodejs.org/en/

Preferably you can download the LTS version as it is the LTS version which has long term support.

nodejs-installation

TEST for successful node installation :

 Type in cmd prompt > node -v > it will give you a version is installed correctly
check-node-installation-version

2. Install Angular CLI using npm

Type this command in command prompt :

 > npm install -g @angular/cli
install-angular-cli-with-npm

Verify angular cli is installed correctly or not

 Type > ng -v
angular-cli-version-check

Great ! – now you have successfully installed angular on your machine. Goto Step 3 and create your first angular app, it’s super simple.

3. Create Angular Basic app – using one single command

 > ng new my-dream-app
create-angular-app-from-cli
It will ask a few questions like:
 Would you like to add routing to your app ? click yes or no
Which stylesheet format would you like to use ? CSS/Less/Sass etc, choose one from the options 

Voila !

You have created your first angular app

Run it …….

Type in command prompt/shell :

> cd my-dream-app
> ng serve 
start-angular-app-ng-serve

now open your web browser and type the url :

localhost:4200

my-dream-angular-app-localhost

Congrats ! – We are done with installing and creating our first basic angular app.

Read Next tutorial -> to Understand the File structure and use of each file in angular app.

Summary

In this tutorial, we learn Step by Step how we can create very first angular app. We Suggest try to follow this tutorial and get started with angular app.
Hope you liked it!


Angular decorators

The decorators in Typescript are like annotations in Java, They are just functions that can be used to add meta-data, properties or functions to the thing they are attached to. They give Angular the ability to store metadata for classes and streamline our workflow simultaneously.

Different Types of Angular Decorators

Before we look at creating a custom decorator and why/how Angular uses them, let’s look at the different types of decorators that Angular offers. There are four main types:

  • Class decorators – e.g. @Component and @NgModule
  • Property decorators for properties inside classes – e.g. @Input and @Output
  • Method decorators for methods inside classes – e.g. @HostListener
  • Parameter decorators for parameters inside class constructors – e.g. @Inject

Examples:

Class decorator Example:

@NgModule({
  declarations: [
    AppComponent, NavbarComponent, routingComponents, HomeComponent, 
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule,
    FormsModule,
    RecaptchaModule.forRoot(), //For Recaptcha
  ],
  providers: [MetaService, Title],
  bootstrap: [AppComponent]
})
export class AppModule { }

And

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
  })
export class AppComponent {
  title = 'ProgrammerToday';
}

List of decorators available in Angular:

  • @NgModule
  • @Component
  • @Injectable
  • @Directive
  • @Pipe
  • @Input
  • @Output
  • @HostBinding
  • @HostListener
  • @ContentChild
  • @ContentChildren
  • @ViewChild
  • @ViewChildren

How to Create custom Decorator ?

Let’s quickly make a decorator that we can use on a class to demonstrate this a little further. 

Example : This decorator is just going to simply log a message to the console:

function LoggerConsole() {
  console.log('This is a logger's log');
}

Apply it over a class, for example

@Console
class SampleClass {
  constructor() {
    console.log('Hi!');
  }
}

OUTPUT

This is a logger’s log

Summary

In this article we learnt what is a decorator, how many types of decorators, a couple of examples and how to create your own custom decorator.

Hope you like it !


Singleton Design Pattern | Implementation

Single Design Pattern is one of the creational style of design pattern. It is often used in scenarios where the class needs only one instance. One of the very common examples which we come across is the Database connection class, when we only need one connection to be shared among other Objects as creating multiple connections/separate connection for every other Object is a costly operation, which would slow down the operations.

How do you design a Singleton Class :

  • Make constructor as private
  • Write a static method which returns Object of same Singleton class. Here, the concept of Lazy initialization in used to write this static method.

How is Singleton Class different from Normal Class?

When instantiating a class, a normal class uses constructor where as a Singleton class will need a static method to create an instance of a class that too only if it is null i.e it is not already in use.

Different levels of making a class Singleton

Method 1: Classic Implementation also called lazy instantiation

class Singleton
{
    private static Singleton obj;
  
    // private constructor to force use of
    // getInstance() to create Singleton object
    private Singleton() {}
  
    public static Singleton getInstance()
    {
        if (obj==null)
            obj = new Singleton();
        return obj;
    }
}
            

Method 2: make getInstance() synchronized

// Thread Synchronized Java implementation of 
// singleton design pattern
class Singleton
{
    private static Singleton obj;
  
    private Singleton() {}
  
    // Only one thread can execute this at a time
    public static synchronized Singleton getInstance()
    {
        if (obj==null)
            obj = new Singleton();
        return obj;
    }
}
            

The main disadvantage of this is method is that using synchronized every time while creating the singleton object is expensive and may decrease the performance of your program

Method 3: Eager Instantiation

// Static initializer based Java implementation of
// singleton design pattern
class Singleton
{
    private static Singleton obj = new Singleton();
  
    private Singleton() {}
  
    public static Singleton getInstance()
    {
        return obj;
    }
}
            

Method 4 (Best): Use “Double Checked Locking”

// Double Checked Locking based Java implementation of
// singleton design pattern
class Singleton
{
    private volatile static Singleton obj;
  
    private Singleton() {}
  
    public static Singleton getInstance()
    {
        if (obj == null)
        {
            // To make thread safe
            synchronized (Singleton.class)
            {
                // check again as multiple threads
                // can reach above step
                if (obj==null)
                    obj = new Singleton();
            }
        }
        return obj;
    }
}              
            

Advantages of Singleton

Saves memory because object is not created at each request. Only single instance is reused again and again.

Summary

In this article we learnt about Singleton Design Pattern and its Implementation.
Hope you liked the article !


Java 8 – Optional

A new class Optional in java.util package used to represent a value is present or absent, its main purpose it to keep us away from too many null checks and NullPointerExceptions

Advantages of using Java 8 Optional :

  1. No more NullPointerException at run-time.
  2. Develop clean and neat APIs.
  3. No more Boiler plate code.
  4. Null checks are not required.

Various methods in Optional object

1. Code to retrieve the wrapped value using get API

Optional<String> opt = Optional.of("programmertoday");
String name = opt.get();

2. Basic Methods from Optional

Optional.ofNullable() method : returns a Non-empty Optional if a value present in the given object. Otherwise returns empty Optional.
Optional.empty() method : useful to create an empty Optional object.

import java.util.Optional;

public class OptionalBasicExample {
    public static void main(String[] args) {
        Optional<String> gender = Optional.of("MALE");
        String answer1 = "Yes";
        String answer2 = null;
        System.out.println("Non-Empty Optional:" + gender);
        System.out.println("Non-Empty Optional: Gender value : " + gender.get());
        System.out.println("Empty Optional: " + Optional.empty());
        System.out.println("ofNullable on Non-Empty Optional: " + Optional.ofNullable(answer1));
        System.out.println("ofNullable on Empty Optional: " + Optional.ofNullable(answer2));   // java.lang.NullPointerException   System.out.println("ofNullable on Non-Empty Optional: " +    Optional.of(answer2));     
       
        } }
        Output:
        Non - Empty Optional:
        Optional[MALE]
        Non - Empty Optional:
        Gender value :MALE
        Empty Optional:Optional.empty

        ofNullable on Non - Empty Optional:
        Optional[Yes]
        ofNullable on Empty Optional:Optional.empty

        Exception in thread "main" java.lang.NullPointerExceptio
        at java.util.Objects.requireNonNull(Objects.java:203)
        at java.util.Optional.<init> (Optional.java:96)
        at java.util.Optional.of(Optional.java:108)

3. Optional – map and flatMap methods

Optional.ofNullable() method returns a Non-empty Optional if a value present in the given object. Otherwise returns empty Optional.
Optionaal.empty() method is useful to create an empty Optional object.

import java.util.Optional;

public class OptionalMapFlatMapExample {
    public static void main(String[] args) {
        Optional<String> nonEmptyGender = Optional.of("male");
        Optional<String> emptyGender = Optional.empty();
        System.out.println("Non-Empty Optional:: " + nonEmptyGender.map(String::toUpperCase));
        System.out.println("Empty Optional    :: " + emptyGender.map(String::toUpperCase));
        Optional<Optional<String>> nonEmptyOtionalGender = Optional.of(Optional.of("male"));
        System.out.println("Optional value   :: " + nonEmptyOtionalGender);
        System.out.println("Optional.map     :: " + nonEmptyOtionalGender.map(gender -> gender.map(String::toUpperCase)));
        System.out.println("Optional.flatMap :: " + nonEmptyOtionalGender.flatMap(gender -> gender.map(String::toUpperCase)));
    }
}

Output:
        Non-Empty Optional::Optional[MALE]
        Empty Optional::Optional.empty
        Optional value::Optional[Optional[male]]
        Optional.map::Optional[Optional[MALE]]
        Optional.flatMap::Optional[MALE]

4. Optional – filter method

import java.util.Optional;

public class OptionalFilterExample {
    public static void main(String[] args) {
        Optional<String> gender = Optional.of("MALE");
        Optional<String> emptyGender = Optional.empty(); //Filter on Optional   
        System.out.println(gender.filter(g -> g.equals("male"))); //Optional.empty   
        System.out.println(gender.filter(g -> g.equalsIgnoreCase("MALE"))); //Optional[MALE]   
        System.out.println(emptyGender.filter(g -> g.equalsIgnoreCase("MALE"))); //Optional.empty   
        } 
}
        
Output:
        Optional.empty
        Optional[MALE]
        Optional.empty

5. Optional – isPresent and ifPresent methods

Optional.isPresent() returns true if the given Optional object is non-empty. Otherwise it returns false.
Optional.ifPresent() performs given action if the given Optional object is non-empty. Otherwise it returns false

import java.util.Optional;

public class OptionalIfPresentExample {
    public static void main(String[] args) {
        Optional<String> gender = Optional.of("MALE");
        Optional<String> emptyGender = Optional.empty();
        if (gender.isPresent()) {
            System.out.println("Value available.");
        } else {
            System.out.println("Value not available.");
        }
        gender.ifPresent(g -> System.out.println("In gender Option, value available."));   //condition failed, no output print   
        emptyGender.ifPresent(g -> System.out.println("In emptyGender Option, value available."));
    }
}

Output:
        Value available.
        In gender Option,value available.

6. Optional – orElse and orElseGet methods

It returns the value if present in Optional Container. Otherwise returns given default value.

import java.util.Optional;

public class OptionalOrElseExample {
    public static void main(String[] args) {
        Optional<String> gender = Optional.of("MALE");
        Optional<String> emptyGender = Optional.empty();
        System.out.println(gender.orElse("<N/A>")); //MALE   
        System.out.println(emptyGender.orElse("<N/A>")); //<N/A>   
        System.out.println(gender.orElseGet(() -> "<N/A>")); //MALE   
        System.out.println(emptyGender.orElseGet(() -> "<N/A>")); //<N/A>   
    }
}

Output:
        MALE
        <N/A>
        MALE
        <N /A>

Summary

In this article we learnt about Java 8 Optional package, its advantages and its variuos methods and implementations.
Hope you liked the article !


Java 8 – Lambdas

Lambda expressions or functions are nameless functions i.e just as anonymous function with no name.

Java earlier being only OOP language there was no existense of functions outside the object or instance. But since java 8 functional programming was introduced you can define functions, give them reference variables or pass them as method arguments and more.

Lambda syntax :

(x,y) -> x+y
1. (parameters) -> expression
2. (parameters) -> {statements;}
3. () -> expression

Some features of Lambda Expressions :

  1. A lambda expression can have zero, one or more parameters.
  2. When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses. e.g. a -> return a*a.
  3. The body of the lambda expressions can contain zero, one or more statements. If body of lambda expression has single statement curly brackets are not mandatory and the return type of the anonymous function is the same as that of the body expression. When there is more than one statement in body than these must be enclosed in curly brackets.

Lambda relationship with Functional interfaces

SAM-Single Abstract Method Inferfaces also called as functional interfaces, java 8 enforces the rule of SAM by annotating these interfaces with a new annotation i.e @FunctionalInferface

        
@FunctionalInterface
public interface Runnable {
    public abstract void run();
}        
      

If you try to add a new method in any functional interface, compiler would not allow you to do this and will throw compile time error.

So, How are they related ?

Let us see an example to find the relation, there is a thread which prints “Test Functional Interface”

        
new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("Test Functional Interface");
    }
}).start();
        
      

When we use lambda here , above code equivalent lambda is like this :

        
new Thread(
    () ->   {
                System.out.println("My Runnable run method");
            }
  ).start();
        
      

In simple words, a lambda expression is an instance of a functional interface.

Examples : Java 8 lambda expression

1. Iterating over a List and perform some operations

        
List<String> list = new ArrayList();
list.add("1");
list.add("2");
  
list.forEach(p ->  {
                    System.out.println(p);
                    //Do more work
                    }
                  );
        
      

2. Create a new runnable and pass it to thread

        
new Thread(
    () -> System.out.println("My Runnable");
).start();  
        
      

3. Sorting employees objects by their name

        
public class LambdaIntroduction {

public static void main (String[] ar){
  Employee[] employees  = {
      new Employee("David"),
      new Employee("Naveen"),
      new Employee("Alex"),
      new Employee("Richard")};
    
  System.out.println("Before Sorting Names: "+Arrays.toString(employees));
  Arrays.sort(employees, Employee::nameCompare);
  System.out.println("After Sorting Names "+Arrays.toString(employees));
        }
  }

class Employee {
  String name;
  
  Employee(String name) {
    this.name = name;
  }
  
  public static int nameCompare(Employee a1, Employee a2) {
    return a1.name.compareTo(a2.name);
  }
    
  public String toString() {
    return name;
  }
}
  
Output:
  
Before Sorting Names: [David, Naveen, Alex, Richard]
After Sorting Names [Alex, David, Naveen, Richard]  
        
      

Summary

In this article we learnt about Java 8 lambda expression, we learnt its syntax, its features, lambda with functional interface and its various other implementations with examples, try it out.
Hope you liked the article !


Java 8 – Functional Programming

Functional programming contains the following key concepts:

  • Functions as first class objects
  • Pure functions
  • Higher order functions

Pure functional programming has a set of rules to follow too:

  • No state
  • No side effects
  • Immutable variables
  • Favour recursion over looping

All the rules may not be applied at all times but you can still benefit by functional programming

Higher Order Functions

A function is a higher order function if at least one of the following conditions are met:
1. The function takes one or more functions as parameters.
2. The function returns another function as result.

      
public class HigherOrderFunctionClass {

  public <T> TestFactory<T> createTestFactory
    (IProducer<T> prod, IConfigurator<T> config) {
      
      return () -> {
          T obj = prod.produce();
          config.configure(obj);
          return obj;
      }
    }
  }
      >
    

Functional Interfaces

A functional interface in Java is an interface that only has one abstract method. By an abstract method is meant only one method which is not implemented. An interface can have multiple methods, e.g. default methods and static methods, both with implementations, but as long as the interface only has one method that is not implemented, the interface is considered a functional interface.

Example of a functional interface:

      
public interface MyInterface {
    public void run();
}
      
      

Here is another example of a functional interface with a default method and a static method too:

      
public interface MyInterface2 {
    public void run();

    public default void doIt() {
        System.out.println("doing it");
    }

    public static void doItStatically() {
        System.out.println("doing it statically");
    }
}
        
      

Notice the two methods with implementations. This is still a functional interface, because only run() is not implemented (abstract). However, if there were more methods without implementation, the interface would no longer be a functional interface, and could thus not be implemented by a Java lambda expression.

Summary

In this article we learnt about the Java 8 Functional Programming, Higher Order functions, functional interfaces and its examples.
Hope you liked the article !