Angular 4 Directives – Lesson 3.3

3.2 Attribute Directives

Here directive is just a class with decorator @Directive and this allows us to specify the directive’s selector.

  • Using custom attribute directive we can change the color, back-ground, font-size etc., of the HTML host element by using ElementRef
  • Renderer class is a built-in service that provides an abstraction for UI rendering manipulations.

Let’s create a custom attribute directive “ShowAlert

Step 1: Create a folder and name it as CustomDirective: /src/app/CustomDirective

Step 2: Now create a typescript file to create your own attribute directive under the associated folder created. And then import Directive, ElementRef, HostListener, Renderer from @angular/core library.

Step 3: And provide your selector name, here I’ve named it as ShowAlert, and create a class that make this directive visible to the component i.e.,add export before the class.

File: app.myDirective.ts

Step 4: Now define contructor for FirstAttrDirective class, and define the style and events using renderer.

For setting up styles,

Renderer.setElementStyle(rendererElement:any, styleName: string, styleValue: string)


For creating events,

Renderer.listen(parentElement: any, name: string, callBack: function)

Step 5: Create your component

File: app.component.ts

Step 6: Add component and Directive in the declaration[ ] of the NgModule  i.e., AppModule

Step 7:  Create a main.ts to bootstrap the NgModule

Step 8: Create a HTML file in /src/

File: CustomDirective.html

Refer required scripts shim.min.js, zone.js, system.src.js, system.config.js and refer the main.js from CustomDirective folder

Output: Default color will be blue, on mouseover font size get increased and changes its color to red, on mouseout will change color to blue and decrease its font size.

Tadaaaa.. 🙂

Angular 4 Directives- Lesson 3.2

Hi friends, in the last session we have learned about built-in directives (ngIf, ngFor, ngSwitch). In this session we will learn,

  • Style and Class Directives ( ngClass, ngStyle)


  • It is used to add and remove CSS classes on an HTML element.
  • CSS Classes can be added in several ways
  1. Using string
  2. Using array
  3. Using object
  4. Using Component methods
  • When using ngClass with object, classes will be added and removed based on the Boolean value that returned.
  • If the value of expression istrue then respective CSS class will be added otherwise that CSS class will be removed from HTML element at run time.

Using String: When using string format, class names must be presented between single quotes with in double quotes “‘class1′” and multiple classes can be separated by space.

File: template.html

File: app.component.ts

Adding styles for the respective classes in component

ngClass using array: When using Array format, each ngClass array item (i.e.,class) must be presented in the string format.

Ex: [ngClass] =”[‘class1′,’class2’]”

File: template.html

ngClass using object: When using object, classes will be formatted in the form of object i.e., each class will be of key and value pairs.

Key: css class name

Value: expression that returns Boolean value

In component file add styles for the respective classes

Using Component Methods: Whereas when using component methods, instead declaring styles statically here styles will be dynamically rendered into template by calling component methods.

  • Depending upon the need/requirement we can pass parameters to the component methods and can dynamically get the required styles.

Ex: [ngClass]=”GetStyles( )”

File: template.html

File: app.component.ts

ngStyle: This directive is used to modify the elements / component styles

  • It accepts an object which defines the elements styles.
  • Both kebab case and lower camel case can be used when specifying style properties.
  • Flexible to add and remove style properties.

File: template.html

File: app.component.ts

Angular 4 Directives – Lesson 3

Hi friends, in the last session we have learnt about how to setup in the local environment. In this session we will learn about Directives. Topics that are going to be covered in this session are

  1. Structural directives (Built-in Directives (ngIF, ngFor, ngSwitch)
  2. Style and Class Directives ( ngClass, ngStyle)
  3. Attribute directives
  4. Host Listener and Host Binding


Overview of Directives:

Directives are the classes that can change the behaviour or appearance of the components by using CSS Classes, CSS Styles and events.

There are three kinds of directives in Angular:

  1. Components—directives with a template.
  2. Structural directives—change the DOM layout by adding and removing DOM elements.
  3. Attribute directives—change the appearance or behavior of an element.

Components are the most common of the three directives. You saw a component for the first time in the QuickStart example.

Structural Directives change the structure of the view. Two examples are NgFor and NgIf in the Template Syntax page.

  • We use (*) before the structural directives, and when we use (*) before ngIf/ ngFor, angular actually recognizes that the current element as a template and it will read the current elements as <ng-template>. Where as in Angular 2.X it reads as <template>.

Attribute directives are used as attributes of elements. The built-in NgStyle directive in the Template Syntax page, for example, can change several element styles at the same time.


*ngIf:  This directive is used for conditional check on the HTML targeting elements. This will work similar to ng-if in Angular 1.X, where the elements will not get rendered into DOM until the condition satisfies. 

Step1: From the quick start example edit the component.ts

File: app.component.ts

Step2: Create a template.html in the app folder

File: template.html

Note: when use * before ngIf, angular treats it as <ng-template>


*ngIf else:  Angular 4  *ngIf has if/else syntax that make sense when you are making ajax calls we can show loading within the page. Where as else block is not existed in Angular 2.

From the above example, add the following html in the template

File: template.html

Angular compiler (JIT or AOT) transforms any <ng-template> elements and directives used with an asterisk (*) into views that are separate from the root component view.

Here when we use (*) before ngIF, angular actually recognizes that the current element as a template, and angular reads it as,


*ngIf then else: *ngIf directive can use two templates, one for If condition and the other for else condition. In the previous example we have seen using template for else condition, now for If condition we need to use then statement.

File: template.html


*ngFor: *ngFor directive is used to iterate through each element of any array, it works similar to For Loop in JavaScript, where in JavaScript we will write for loop within the <script> tag, but in angular we use *ngFor in the HTML as directive for any kind of elements.

From the above example add the following code in the component file

File: app.component.ts

File: template.html

Here we are using for..of, where

  1. for..of iterates through items and returns values
  2. iterates through properties and  returns list of keys
  3. let is a keyword which is a dynamic datatype of ECMA script.
  4. emp is a temporary variable that hold the current employee from the employees array.
  5. employees is the array of items

Here the let can also create a index as a reference of the current item.

Here index is a built-in keyword of angular framework which can be used in *ngFor. Where angular renders the above code as follows.


*ngFor with select tag:


ngSwitch: ngSwitch works similarly the switch statement that we use in C# / java etc., Here for defining case we use *ngSwitchCase and for default case we use *ngSwitchDefault

From the above example using the same list of employees, we have created a example

Setup for local environment in Visual Studio – Lesson 2

Setting up Angular2/Angular4 is a quite complex, it needs a lot of work when compared with the installation for Angular1.X applications.

To setup with the quick start files follow these steps:

Step1: Install Node JS and npm

Step2: Install visual studio 2015 update3

Step3: Configuring External Web Tools.

Step4: Install Typescript

Step5: Download quick start files

Step6: Create ASP.NET Project

Step7: Copy the quick start files into your ASP.NET Project

Step8: Restore Packages

Step9: Build and Run

Install Node and NPM
  • Angular 2/4 is developed with compatible latest versions of Node, where you must have Node JS version 4.6.X or higher and npm 3.X.X or higher.
  • Older versions produce errors
  • Before installing make sure whether you have already installed Node JS before. For checking the Node JS and npm versions follow these commands in command prompt.

For Node JS: node –v

For npm: npm –v

  • If the PC don’t have Node JS installed it will show you like “node” is not recognized as an internal or external command, “npm” is not recognized as an internal or external command. Or if your PC has older version than the required please update to the latest versions.
  • For installing latest version of Node JS and npm go to
  • Your first step will be completed if you have installed the required versions.


Install Visual Studio 2015 Update 3

Note: For studio 2017 versions can ignore this step

Minimum requirement for developing Angular2/ Angular4 applications is Visual Studio 2015 Update3 because the earlier versions do not follow the best practice for developing applications with Typescript.

  • To check the version of Visual Studio 2015

Open Visual Studio 2015    go to Help    click on About Microsoft Visual Studio

  • If you don’t have install Visual studio 2015 update 3


Configure External WebTools
  • We need to configure Visual Studio to use the global external web tools before the tools that ship with visual studio.
  • Go to Visual Studio    Click on Tools    Options    Expand Projects and Solutions    click on External Web Tools    now in the right hand side move $(PATH) entry above the $(DevEnvDir) This tells the visual studio to use the external tools like (npm) found in the global path before using its own version of the external tools.
  • Now click OK and restart the Visual Studio to reflect these changes. Visual Studio now looks first for external tools in the current workspace and if it doesn’t find them, it looks in the global path. If Visual Studio doesn’t find them in either location, it will use its own versions of the tools.


Install Typescript
  • To develop Angular applications we need Typescript 2.2.0 or its higher versions, as Visual studio Update3 doesn’t have such specifications we need to install it externally.
  • Before installation we can check our Typescript version in the Visual Studio

Open Visual Studio 2015    go to Help    click on About Microsoft Visual Studio


Download Quick start files

You can download the quick start files from Git hub and then extract the files.


Create ASP.NET Project

Create ASP.NET 4.X or above project in the visual studio

Go to Visual Studio       File      New     Project    select Visual C# under Templates    click on ASP.NET Web Application     select Desired Templates    give the project name and click on OK.


Copy Quick start files into ASP project

Copy the quick start files into your project, but all the files are not necessary to be included into your project. So copy only selected files from the extracted folder.

Copy the following files into your .csproj

  • Src
  • Bs-config.json
  • json
  • json


Restore  Packages

Restore the packages required for your application

  • For restoring packages right click on json     select Restore Packages. This uses npm to install all the packages defined in package.json.
  • In between you can open the Output window to watch the npm commands that are executed. Simply we can ignore the warnings.
  • After you see the message Installing Packages Complete make sure that your project doesn’t includes node_modules


Build and Run

 File: /src/app/component.ts

In the above example that we have copied from the quick start files,

  1. In the first statement we are importing Component Package from angular/core package directory. After restoring package.json in /node_modules you can see all the packages that are downloaded using npm commands.
  2. In the second statement according to angular,
    1. @ is called –> decorator
    2. @Component  is called –> Component decorator
    3. selector –> xml tag / custom html tag
    4. template –> view for the component

Complete syntax of component, (Component decorator + class followed by the component decorator)

3. In the third statement we are exporting the component, to make it visible to other modules in our angular application.

  • After Installing packages build the Application.
  • To run the application open Command Prompt     go to your Project Directory       execute command npm start.
  • When this command is executed,
  • firstly it will launch typescript compiler and compiles the application with the following command tsc –p src/
  • Now it will start the lite-server and launches the browser where you can see the

Output: Hello Angular

  • But if you run the html by pressing F5 in visual studio it will not show the same output.

To Run in VS with F5 follow these steps

    1. In html, change base href from <base href=”/”>to <base href=”/src/”>.
    2. Also in html, change the scripts from node_modules to /node_modules with a slash
    3. In src/systemjs.config.js, near the top of the file, change the npm pathto /node_modules/ with a slash.
    4. After these changes npm start command no longer works, you must choose to configureeither for F5 with IIS or for npm start with the lite-server.
    5. Now run the application using F5

Differences between Angular JS and Angular 2

1.4 Differences between Angular JS and Angular 2

  • First thing we need to keep in mind is Angular 2 is not an upgrade version for Angular JS. Because Angular 2 is completely different compared to Angular JS architecture.
  • Architectures of Angular 2 has designed this as a new language which is no more uses MVC pattern. It’s a complete rewrite by the same Angular JS team.
  • Angular team announces that Angular 1.X is called as “AngularJS”, where Angular 2 will be called as just “Angular”
  • Let’s see the main differences between Angular JS and Angular 2

Introduction to Angular 4 – Lesson 1

Hi guys. In this tutorial we are going to learn about Introduction to Angular 4.

Introduction to Angular4

  1. What is angular?
  2. What are the advantages of learning Angular?
  3. Why should we choose angular?
  4. Differences between Angular Version (1.X, 2, 4)

1.1 What is Angular?

  • Perquisite to learn Angular 4 is Javascript and Typescript.
  • If someone ask you this question, then you must be aware of what is JAVASCRIPT. Because javascript is the basic for all the scripting languages like Angular4, ReactJs, NodeJs, etc… Here are few languages that are supersets of javascript that will generate Javascript on compiled.

  • The Aim of Javascript is to make the HTML page dynamic. Now if you have a question that what is dynamic, “Making a HTML Dynamic mean, nothing but changing the data in the HTML page by an action done by the user”.
  • Angular 4 is a Framework which supports,
    •  Databinding (one-way/two-way),
    • OOPs Features (Inheritance, Interfaces, Encapsulation, Abstraction). One thing clear is Angular 4 doesn’t support polymorphism.
    • Angular uses its own routing to develop Single Page Applications (SPA).
    • Services like HTTP.
    • Dependency Injection.
    • Animations.
    • Lazy loading application.
    • ES5 and ES6 (ECMA script)


  • Angular is a Framework but not a library, where the difference is pretty simple that library is just an add-on for a framework. But framework gives you a platform to create the application.
  • Angular is a Structured Framework which is very useful to maintain the DOM and to manipulate the DOM. Why do we call it a Structured F/w is because Angular has its own specified architecture to create an application. To create a new application we must create in the following structure.

  • Angular 4 uses Typescript language to create an application. So perquisite for learning Angular 4 is Javascript and Typescript. Where Typescript is a superset of javascript which will generate javascript on compile. For compiling typescript it uses TSC (Typescript compiler).
    Ex: You have sample.ts.
    On compiling sample.ts using tsc –compiler it will generate two more files

1.2  What are the advantages of learning Angular?

  • Main advantage is the Consistency and it is easy to Maintain.
  • It has a Component-based architecture that provides a higher quality of code
  • Google has announce the LTS( Life time support) for Angular 4.
  • Angular4 is developed using Typescript enabling us to optimize the code using OOPS concept.
  • Angular is very famous for Single Page Application (SPA).
  • Two-way data binding reduces the development time for synchronizing View and Model.
  • Dependency Injection allows us to reuse the code, and we can import third party libraries to Angular by using DI (Dependency Injection), and where we can share the various services into other services or components.
  • Directives are very helpful for developers to change the behavior of the HTML elements in Document Object Model (DOM), permitting us to create dynamic and rich content with HTML. Angular provides us the facility to create our custom Directives.

1.3 Why Should we choose Angular ?

  • Angular is a open source framework which we can freely download, no need for pay money for
    this framework.
  • It makes client side programming very easy.
  • The tooling support is as good as on Java or .Net platforms.
  • Angular uses TypeScipt language, Its object oriented and supports core features like interfaces and classes. TypeScipt code analyzer warns you about the errors as you type.
  • Data Binding is a primary feature of angular, it can be implemented in 2-Ways,
    • One-way data binding
    • Two-way data binding
  • First time in client side frameworks angular introduced this data binding concept, this
    feature will reduce lot of client side coding related to data presentation (HTML view).
  • It’s a pattern language it uses HTML and extends the behaviour of the HTML elements with directives(for example, <myPaging></myPaging>. This improve code readability.
  • Dependency injection give you a clean way to implement loose coupling between components and
    services. Binding and events allows you to create reusable and loosely coupled components.
  • Performing validations will becomes so simple, just we need to know about HTML5 Validation attributes (required, pattern, max-length, min-length).
  • Unit testing becomes easy in Angular.
  • Angular applications can run on all major browsers and smart phones, including Android and
    IOS based phones/tablets.
  • It has own Routing support for single page application(SPA), in SPA only main page will load from
    server remaining all requestes are processed at clint side without reloading the whole page.

Angular 2/4 Router no longer navigates when navigating to the current URL

The concept we need to understand here is that the,

  1. Angular route will navigate only when it navigates to a different route using [routeLink] attribute.


  • Force reload/ refresh the current route using RouteReuseStrategy
  • Now we need to set this.router.navigated = false; after navigation completes.

  • Window.scrollTo(0,0) , will move your page scroll bar to the top position.

Dynamic Tree Using Angular 2/4

Hello Angular Experts and Beginners, if you really stuck in a situation how to form dynamic tree using  <ul> and <li>. I’m sure that this blog will definitely helps you.

Download Source Code

Step 1: Prequisite you should have a json data in a format as follows.

Step 2: Once you have data create the following structure in your angular project

File: test.json



Step 3: Creating declaration file for javascript file.

Here we are now creating a declaration file for the javascript file (myscript.js) using Ambients in typescript.

For reference of TypeScript Ambients please follow this post Typescript Ambients

File: myscript.js

File: myscript.d.ts

Step 4: Once declaration file is ready then create component and template and add reference of declaration file in the component

File: app.component.ts

File: template.html

Note: In the below code i’ve created Recursive ng-template. 

  1. #mylst1 is a template reference variable for the ng-template
  2. let-list –> here we are defining a local variable. let is a key word to declare variables in typescript.
  3. ng-container –> It’s a container to group html elements, which is same as ng-include  in AngularJS. For reference please follow the link 
  4. $implicit –> It is used to set the value for our ng-template using context property of ngTemplateOutlet.

File: app.module.ts

File: main.ts

Step 5: Create a html file in src/DynamicTree.html folder

File: DynamicTree.html


Date time picker in angular 2/4

Download source code

To add datepicker and timepicker in angular 2/4 forms we have a good builtin components given by ng2-bootstrap. No need to go for other third party date pickers which might work or may not. Ng2-bootstrap provides us all the feature of the normal bootstrap which we use daily. So you can just blindly remove the bootstrap and replace it with ng2-bootstrap/ ngx-boostrap.

Step 1: First you need to install the package using npm 

Install commands

  • Open command prompt –> go to you project directory –>  npm install ng2-bootstrap –save –> run command
  • Similarly install  npm install moment –save

Step 2: Now  configure the ng2-bootstrap in systemjs.config.js

Go to systemjs.config.js,  add the moment and ng2-bootstrap npm packages to the map  as below

Now add these packages in the packages

Step 3 : Import DatepickerModule, TimepickerModule  in Root NgModule

import { DatepickerModule, TimepickerModule } from ‘ng2-bootstrap’;


Step 4 : Create component and add the components to your html