How to create a component in angular

In this tutorial we will understand how to create a component in angular application. We have already seen what is an angular component though, but we will look into it again. In Angular each functionality can be made as a component which can be used in the entire application just by importing it. So now we will look into the steps to create a component in angular.

Let’s Begin ! – Just 2 Steps

Step 1 :

create a new directory inside app directory for better management of components(not mandatory)

> mkdir contact

Step 2 :

Now, create component by using command as below

> ng g c contact –flat

-g : to generate

-c : for component

–flat in an option used to stop create a directory of same name as the name given in the above command, and create all files in the current directory. It puts the file in src/app instead of its own folder.

So the above command creates 4 files as shown below in this snapshot.

create-angular-component-using-angular-cli

This creates 4 files :

contact.component.html file : file write the html content of your page exists.

contact.component.spec.ts : file where you have the test cases

contact.component.ts : file where you write the functionality and logics in this typescript.

contact.component.css : file where you write the css content of the page.

 Next, Include this component in main app.component.html 

by including the tag in app.component.html as per the selector created in contact.component.ts

<app-contact></app-contact>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-contact',
  templateUrl: './contact.component.html',
  styleUrls: ['./contact.component.css']
})
export class ContactComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}

Summary

In this tutorial, we learnt how to create a component in angular application and add the created component using its html selector tag to any other component like AppComponent here. Enjoy learning Angular.
Hope you liked it!


How to add bootstrap and other js in angular application

In this tutorial we will understand how to add bootsrap css in angular app.

After creating the angular basic app using ng new my-dream-app install the bootstrap using the below command.

1. Install bootsrap using npm cli

> npm install bootstrap –save

Type this command from your project directory eg: (c:\workspace\my-dream-app)

install-bootstrap-css-in-angular

Note: In case you see a Warning as below in the snapshot, it means you need to navigate to your project structure and then execute the bootstrap install command, if you see a warning of package.json no such file warning it simply means you must install bootstrap from this directory where the file is present.

install-bootstrap-css-in-angular

2. Add bootstrap css entry in angular.json

Open angular.json file, locate styles and add bootstrap file path to the styles section. Like this,

angular-json-styles-add-bootstrap

3. Verify – bootstrap has been installed successfully or not?

Let’s add a table with few extra bootstrap classes to see bootstrap is working fine or not

In your app.component.html

add the following html table code:

<div class="container">
  <table class="table table-dark table-hover table-striped">
    <thead class="thead-light">
      <tr>
        <th>Name</th>
        <th>Age</th>       
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>Jack</td>
        <td>30</td>
      </tr>
      <tr>
        <td>Jill</td>
        <td>31</td>       
      </tr>
      <tr>
        <td>Robert</td>
        <td>32</td>       
      </tr>
    </tbody>
  </table>
</div>

Now You would see this in your browser: localhost:4200

angular-bootstrap-css-table

AND earlier without Bootstrap, it would look like as shown below:

angular-table-without-bootstrap-css

Summary

In this tutorial, we learnt about how to add bootstrap in angular project and how to make use of it by adding a simple bootsrap css classes in html table, Enjoy using bootstrap with angular now, it makes life easier.
Hope you liked it!


Angular app Files and its explanation / Files Explanation

In this tutorial we will understand the angular file-structure of a project and see each default file, folder created and its uses.

angular-project-file-structure-visual-studio-code

Files used in Angular 7 App folder

  • src folder: This is the folder which contains the main code files related to your angular application.
  • app folder: The app folder contains the files, you have created for app components.
  • app.component.css: This file contains the cascading style sheets code for your app component.
  • app.component.html: This file contains the html file related to app component. This is the template file which is used by angular to do the data binding.
  • app.component.spec.ts: This file is a unit testing file related to app component. This file is used along with other unit tests. It is run from Angular CLI by the command ng test.
  • app.component.ts: This is the most important typescript file which includes the view logic behind the component.
  • app.module.ts: This is also a typescript file which includes all the dependencies for the website. This file is used to define the needed modules to be imported, the components to be declared and the main component to be bootstrapped.
  • e2e folder: end-to-end testing files for the project are contained here.

Other Important files

  • package.json: This is npm configuration file. It includes details about your website’s package dependencies along with details about your own website being a package itself.
  • package-lock.json: This is an auto-generated and modified file that gets updated whenever npm does an operation related to node_modules or package.json
  • angular.json: It is very important configuration file related to your angular application. It defines the structure of your app and includes any settings associated with your application. Here, you can specify environments on this file (development, production). This is the file where we add Bootstrap file to work with Angular 7.
  • .gitignore: This file is related to the source control git.
  • .editorconfig: This is a simple file which is used to maintain consistency in code editors to organize some basics such as indentation and whitespaces.
  • assets folder: This folder is a placeholder for resource files which are used in the application such as images, locales, translations etc.
  • environments folder: The environments folder is used to hold the environment configuration constants that help when building the angular application. The constants are defined in 2 separate .ts files (environment.ts and environment.prod.ts), where these constants are used within the angular.json file by the Angular CLI. For example, if you run the ng build command, it will build the application using the development environment settings, whereas the command ng build ?prod will build the project using the production environment settings.
  • browserslist: This file is used by autoprefixer that adjusts the CSS to support a list of defined browsers.
  • favicon.ico: This file specifies a small icon that appears next to the browser tab of a website.
  • index.html: This is the entry file which holds the high level container for the angular application.
  • karma.config.js: This file specifies the config file for the Karma Test Runner, Karma has been developed by the AngularJS team which can run tests for both AngularJS and Angular 2+
  • main.ts: As defined in angular.json file, this is the main ts file that will first run. This file bootstraps (starts) the AppModule from app.module.ts , and it can be used to define global configurations.
  • polyfills.ts: This file is a set of code that can be used to provide compatibility support for older browsers. Angular 7 code is written mainly in ES6+ language specifications which is getting more adopted in front-end development, so since not all browsers support the full ES6+ specifications, pollyfills can be used to cover whatever feature missing from a given browser.
  • styles.css: This is a global css file which is used by the angular application.
  • tests.ts: This is the main test file that the Angular CLI command ng test will use to traverse all the unit tests within the application and run them.
  • tsconfig.json: This is a typescript compiler configuration file.
  • tsconfig.app.json: This is used to override the tsconfig.json file with app specific configurations.
  • tsconfig.spec.json: This overrides the tsconfig.json file with app specific unit test configurations.

Summary

In this tutorial, we learnt about the file structure of the angular application, it’s various files and folder structures and the type of information it stores.
Hope you liked it!


Git Merge Vs Rebase

When to use git merge ?

Use it as a default scenario when you don’t want to bother about the commit history and want to avoid problems, anyways it comes as default with git pull.

When to use git rebase ?


Use it to make your commit history look more clear and consistent.

Can be used for temporary local branches(like feature branches).

You can use git rebase -i(interactive) for rewriting the local commit histories into a neat one before you push it to the remote repository.

Difference between Merge and Rebase – When to use what


Git MergeGit Rebase
git merge apply all the unique commits from one branch to the other in one commitgit rebase takes all the unique commits from both the branches and applies them one by one
merge does not rewrite any commit history but just add one new onerebase rewrites the commit history but doesn’t create extra commit to merge

Summary

In this tutorial we looked into the difference between git merge and git rebase and when to use what.
Hope you liked it!


Gradle Build Tool – Guide

Gradle Build Tool is an open source, advanced general purpose build management system. It is built on ANT, Maven, and lvy repositories. It supports Groovy based Domain Specific Language (DSL) over XML.

Gradle handles two major things using its build script – one the project build and the other is tasks.

A Task – means small chunk of work which the build performs and a project is made of many tasks, examples : creating a jar package, compiling files or any other target like in ANT build xml file.

Build a gradle script

Gradle used groovy language to make build scripts, it follows UTF-8 standard

File name : build.gradle

Sample script to run a task

 
 task print {
            doLast {
            println 'ProgrammerToday'
                    }
            }
        	

Execute the script : C:\> gradle -q print

To build source files from other folder

Do the following in the build script, for example if the folder name is src instead of the usual src/main/java

 
apply plugin: 'java'
sourceSets {
    main {
      java {
          srcDir 'src'
      }
    }
  
    test {
      java {
          srcDir 'test'
      }
    }
}
        

Adding dependencies in the gradle build file

apply plugin: 'java'

repositories {
    jcenter()
}

dependencies {
    compile 'org.slf4j:slf4j-api:1.7.12'
    testCompile 'junit:junit:4.12'
}
        

To run a main class from the build file

Assuming there is a class Test with a main method

apply plugin: 'java'

repositories {
    jcenter()
}

dependencies {
    compile 'org.slf4j:slf4j-api:1.7.12'
    testCompile 'junit:junit:4.12'
}

jar {
    manifest {
      attributes 'Main-Class': 'com.gradle.main.Application'
    }
}
        
To compile the above code

dir\> gradle tasks
dir\> gradle assemble
dir\> gradle build

Gradle installation | prerequisites

Steps to install gradle :

  1. Install and set the environment variables
  2. Install gradle and set the environment variables
    GRADLE_HOME & PATH just as in for jdk
  3. Verify the gradle installation
    C:\gradle -v

Summary

In this tutorial we saw how to use Gradle as a build tool, how to create a gradle build script, how to add dependencies in gradle build file, we learnt how to run a main class file from the gradle build file and its installation.
Hope you liked it !


Maven Build Tool – Guide

Maven is a build automation and a project management tool, mainly used for Java projects. Maven project structure and contents are declared in an xml file called pom.xml, referred as Project Object Model (POM), pom is the heart of the maven build system

Learn Maven in 5 minutes !

Step 1 :
Download maven zip extract from here

Step 2 :
Unzip the dowloaded file and set the Environment variables
In Windows:
M2_HOME : C:\Program Files\Apache Software Foundation\apache-maven-3.3.1
M2=%M2_HOME%\bin
MAVEN_OPTS=-Xms256m -Xmx512m

Step 3 :
Check if maven configuration is done successfully :
C:\>mvn –version
It should display information like below, if it does show something like below, it means the maven installation/configuration is successful.
Apache Maven 3.6.0 (97c98ec64a1fdfee7767ce5ffb20918da4f719f3; 2019-01-24T10:31:37+02:00)
Maven home: C:\Program Files\Apache Software Foundation\apache-maven-3.6.0\bin\..
Java version: 1.8.0_161, vendor: Oracle Corporation, runtime: C:\Program Files\Java\jdk1.8.0_161\jre
OS name: "windows 7", version: "6.1", family: "windows"

Create a Project

Create a directory in your machine anywhere, eg: mkdir test

Goto test : C:\>cd test

Run the command :
mvn archetype:generate -DgroupId=com.programmertoday.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false

This archetype : generate goal created a simple project based upon a maven-archetype-quickstart archetype and will create a directory with the name given in -DartifactId

When you go inside this directory: C:\test>cd my-app
you will see a pom.xml file and a src directory

The src dir will have sub folders : src/main/java/com/programmertoday/app/App.java & src/test/java/com/programmertoday/app/AppTest.java

Pom.xml file will look like this :

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
 
  <groupId>com.programmertoday.app</groupId>
  <artifactId>my-app</artifactId>
  <version>1.0-SNAPSHOT</version>
 
  <properties>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>
 
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

Build the Project

C:\test\my-app>mvn package
Output[INFO] ----------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ----------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Thu Jan 24 21:34:52 CEST 2019
[INFO] Final Memory: 3M/6M
[INFO] ----------------------------------

This command is a phase rather than a goal in the previous mvn archetype:generate command, So when a phase is given Maven will execute every phase in a sequence upto and including the one defined. For example if the phase given is C:\test\my-app>mvn compile, then the phases that actually get executed are:
1. validate
2. generate-sources
3. process-sources
4. generate-resources
5. process-resources
6. compile

After mvn package, the command has created the package as the jar

Now you can run the jar’s main method by the command:
java -cp target/my-app-1.0-SNAPSHOT.jar com.programmertoday.app.App

It prints the output on the console

Hello world !

Maven Phases

List of most common default lifecycle phases :

  • validate: validate the project is correct and all necessary information is available
  • compile: compile the source code of the project
  • test: test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package: take the compiled code and package it in its distributable format, such as a JAR.
  • integration-test: process and deploy the package if necessary into an environment where integration tests can be run
  • verify: run any checks to verify the package is valid and meets quality criteria
  • install: install the package into the local repository, for use as a dependency in other projects locally
  • deploy: done in an integration or release environment, copies the final package to the remote repository for sharing with other developers and projects.

There are two other Maven lifecycles of note beyond the default list above. They are

  • clean: cleans up artifacts created by prior builds
  • site: generates site documentation for this project

Alternate ways of using Maven :

  • Build Maven project using eclipse IDE : Download maven plugin in eclipse and use.
  • Build Maven project using Intellij IDE : You can use the external maven as configured above and use the Intellij console to run the maven goals.

Summary

In this tutorial we saw how to use maven as a build tool, how to create a maven based project, sample POM.xml, building the project and learn about maven phases.
Hope you liked it !


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 !