Introduction to Angular 2 Components

A component is a main building block of an Angular 2 application, and an application may have any number of components. We can consider a component a particular view of the application with its own logic and data.

In AngularJS 1.0, there was the concept of controllers, $Scope, and directives to bind data and logic to the view or to create custom elements on the view. In Angular 2, components perform all the tasks that were performed by controllers, scopes and directives. Data, logic and custom elements can all be created or added to the page using components in Angular 2.

Angular 2 applications are built around components, and we can consider component as a view with its own:

  • Template
  • Application Data
  • Logic
  • Styles, and more

Let’s Create Our First Component

Let us start with creating a very simple component to display “Hello World” on the page.

appcomponent.component.ts

 

There are mainly three steps to create a component

  1. Create a class and export it. This class will contain data and the logic.
  2. Decorate the class with @component metadata. Basically, metadata describes the component and sets the value for different properties, so that a TypeScript class can be used as an Angular 2 component.
  3. Import the required libraries and modules to create the component.

Three steps discussed above can be visualized in the diagram below:

image

As you can see, the Angular 2 component consists of:

  • A TypeScript Class to hold data and the logic;
  • HTML template and styles to display data in the app. It is also called as a view, which is seen by the user on the screen to interact.
  • Metadata which defines the behavior of a component. Component metadata is applied to the class using the @Component decorator. Different behavior of the component can be passed as properties of the object, which is and input parameter of the @Component decorator.

Read full article on the Infragistics blog

What are Closures in JavaScript?

Read full article on the Infragistics Blog

A JavaScript closure is a function which remembers the environment in which it was created. We can think of it as an object with one method and private variables. JavaScript closures are a special kind of object which contains the function and the local scope of the function with all the variables (environment) when the closure was created.

image

To understand closures, first we need to understand SCOPING in the JavaScript. We can create a variable or a function in three levels of scoping,

  1. Global Scope
  2. Function or local scope
  3. Lexical scope

I have written in details about scoping here, but let’s take a brief walkthrough of scoping before getting into closures.

Scopes in JavaScript

As soon as we create a variable, it is in a Global Scope. So, if we have created a variable which is not inside any function, it is in a global scope.

Read full article on the Infragistics Blog

Different ways of injecting dependency in an AngularJS Application

When you start learning the very first characteristics of AngularJS, you may come across something called Dependency Injection (DI): the premise that AngularJS injects dependencies whenever an application needs them. As a developer, our task is only to pass the dependency to the module and everything else will be taken care by AngularJS.

To create a controller, we pass $scope object and other dependencies to the module’s controller function. For example, to create a ProductController, we are passing $scope object and Calculator service dependencies. As a developer our job is to pass the dependencies and AngularJS will inject them whenever the application needs them.

As a developer, we really don’t care about how AngularJS injects dependencies – we don’t need to know how the injection process works to develop applications.  However, it is better if we know different ways of passing dependencies. In AngularJS, dependencies can be passed in three possible ways. They are as follows:

  • Passing a dependency as Function Arguments
  • Passing a dependency as Array Arguments
  • Passing a dependency using the $inject service

Let us explore these options one by one.

Passing a dependency as a Function Argument

Perhaps most of the time you pass a dependency as a function argument, which is perfectly fine. For example, we pass a $scope object to create a controller as shown in the listing below:

Read full article on the Infragistics blog

What is a Provider () in AngularJS?

The provider() function allows us to create a configurable service where we can set input per application for the service created using the provider (). For example, if we need to set API key to access a service on the application level, we can set that in the module config and pass input to the provider using the $provide service. All the others ways to create services internally use the $provide service.

Creating a service using $provide service in module.config

Let us start by creating a very simple service using the provider() function.

	
app.config(function ($provide) {
    $provide.provider('globalsetting', function () {
        this.$get = function () {
            var appname = "Lawyer App";
            return {
                appName: appname
            };
        }
    })
});

Let’s explore what is going on in the above snippet. To create a service using provider, we need to use the $provide service. The provider function of the $provide service takes two parameters: the name of the service and the function. A provider function must have a $get function. To create a simple service using the provider(), we need to perform following five steps:

  1. Inject the $provide service in the app config method
  2. Create a provider using the provider() function
  3. Pass two parameters to the provider() function: the name of the service and a function
  4. The provider function must contain a $get function
  5. Return an object literal from the $get function

We can use the globalsetting service created using the provider by injecting it in a controller as shown in the listing below:

Read full article on the Infragistics blog

Getting started with TypeScript

TypeScript is superset of JavaScript created by Microsoft. TypeScript – according to its website – “lets you write JavaScript the way you really want to. TypeScript is a typed superset of JavaScript that compiles to plain JavaScript”.

Some features of TypeScript include:

  • Support standard JavaScript
  • Static typing
  • Encapsulation using the classes and the modules
  • Constructors, properties and functions supports
  • You can define interface
  • Lambda support Lambda support
  • Syntax checking
  • Type annotations
  • Static or dynamic loading of module contents

TypeScript can be summarized in the following points:

  • TypeScript is syntactic sugar for JavaScript
  • TypeScript syntax are the superset of ECMASCRIPT 5 syntax.
  • TypeScript compiler converts or compiles the TypeScript file into a JavaScript file locally.
  • TypeScript does not reorder the variable declaration
  • TypeScript syntax includes various proposed features of ECMASCRIPT 6
  • TypeScript complies with module codes generation which can by loaded statically or dynamically.
  • TypeScript works with type inference

This post will help you to get started with TypeScript, setting up the environment for TypeScript development in the Visual Studio and Sublime Text. At the end of the post we will create a simple TypeScript program in Visual Studio.

Read the full article on the Infragistics blog

Prototypical inheritance in JavaScript

Read full post on falafel blog

Before we can understand prototypical inheritance, let us start with a problem statement. You have a student for whom you need to:

  • Calculate their grade
  • Print the grade

In JavaScript this can be simply implemented as follows:


var studentMarks;
var studentGrade;

function FindGrade(studentMarks) {
    if (studentMarks >= 80) {
        studentGrade = "A";
    }
    else {
        studentGrade = "B";
    }
}

function PrintGrade() {
    console.log("Student Grade is " + studentGrade);
}

FindGrade(60);
PrintGrade();

There are some inherent problems in the above approach:

  • Variables are defined globally
  • Code maintenance is tough as the functionality grows
  • Code debugging is tough
  • Code testing is tough

The major problem in the above code is that neither the PrintGrade nor the FindGrade functions are reusable. Any future requirements in the find grade logic or in the print logic will require a change in the existing code, and that may introduce new bugs and require testing again. As a developer we may not want this.

Let us go ahead and refactor above code as follows:

Read full post on falafel blog

What is strict mode in JavaScript?

Have you ever noticed use of strict keyboard as shown in following image anywhere?

 

When I start creating application for Windows Store (Metro App), I noticed this on the top of the default.js file. Well it is nothing but a way to tell JavaScript for better coding and error checking in JavaScript code. If you put strict mode then you are not allowed to do many things in JavaScript code like assigning value to a read only variable.

You can put strict mode restriction

  1. On the function level
  2. On the page level   

 You can put strict restriction on function level as following

Now let us try to put some code in above function. In below code we are assigning value to a variable which is not declared. We have also put function is the strict mode.

When try to call this JavaScript function, you will get error as following. You see in the error message that “Variable undefined in strict mode”. If you go ahead and remove strict mode from the function then you should able to call the function.

If you have put strict mode then you will get error if you try to perform following operations.

  1. Assigning value to non-declared variable
  2. Assigning value to read only variable
  3. Defining duplicate property
  4. Defining duplicate parameters in a function
  5. Using future reserved keywords like interface, let, package etc.
  6. Cannot defined a function inside if-else or for statement

There are many other operations will give you error in strict mode. I hope now purpose of strict mode is clear to you. Thanks for reading!

Flyout control in Windows 8 HTML JavaScript Metro Application

In this post, I will discuss how to work with Flyout in Windows 8 Metro application. Flyout is a type of UI surface in Windows 8 metro application. It is used to show simple message or popup. If user touches or clicks anywhere on the screen then Flyout disappears. It usually used to collect simple user information or show some message. Flyout should be as simple as possible. It should not have complex UI. A usual flyout can be like below,

image

Flyout can be created deceptively as below.

clip_image002

Inside Flyout we can put any HTML elements. As purpose of this post I am going to put sports as option and user can select out of that options. After putting sports options Flyout div will get modified as below,

clip_image004

User can select sports from above Flyout. As the design of the page, we have put a button and output div. We are going to popup a fly out on click event of a button. On selection of a sports option in Flyout, we will display that in output div and Flyout will disappear.

Default.html


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>WinWebApp1todelete</title>
<!-- WinJS references -->
<link rel="stylesheet" href="/winjs/css/ui-dark.css" />
<script src="/winjs/js/base.js"></script>
<script src="/winjs/js/ui.js"></script>
<script src="/winjs/js/binding.js"></script>
<script src="/winjs/js/controls.js"></script>
<script src="/winjs/js/animations.js"></script>
<script src="/winjs/js/uicollections.js"></script>
<script src="/winjs/js/wwaapp.js"></script>
<link rel="stylesheet" href="/css/default.css" />
<script src="/js/default.js"></script>
</head>
<body>
<button id="butonchooseSports" type="button"
style="margin-left:900px;
margin-top:20px;font-size:x-large">
Choose Sports
</button>
<div id="sportsFlyout" data-win-control="WinJS.UI.Flyout" aria-label="{Format text flyout}">
<label for="scenario3TextColor">choose sports</label>
<br />
<select id="scenario3TextColor">
<option value="cricket">Cricket</option>
<option value="football">FootBall</option>
<option value="hocky">Hocky</option>
<option value="tenis">Tenis</option>
<option value="rugby">Rugby</option>
<option value="golf">Golf</option>
</select>
</div>
<div style="margin-left:900px;
margin-top:300px;font-size:x-large" id="outputDiv"></div>
</body>
</html>

In code behind on click event of the button Flyout can be shown as below function.

clip_image002[8]

Here we are,

  • Selecting Flyout div as win control.
  • Calling Show function to display Flyout.
  • There are input parameters of Show function. First parameter is id of button. On click event of this input button Flyout will get displayed.
  • Second parameter is position of the Flyout. Other possible value of this parameter could be top.

We are putting all code together as below,

Default.js


(function () {
'use strict';
// Uncomment the following line to enable first chance exceptions.
// Debug.enableFirstChanceException(true);
var choosesportsbutton;
WinJS.Application.onmainwindowactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
// TODO: startup code here

WinJS.UI.processAll().then(function () {
choosesportsbutton = document.getElementById("butonchooseSports");
choosesportsbutton.addEventListener('click', showflyout);



});
}

function showflyout()
{
var flyOut = document.getElementById("sportsFlyout").winControl;
flyOut.addEventListener('change', ChangedSportsValue);
flyOut.show(choosesportsbutton, "bottom");
}

function ChangedSportsValue(e) {

var res = document.getElementById('scenario3TextColor').value;
document.getElementById('outputDiv').innerText = "You have selected " + res;
}
}

WinJS.Application.start();
})();


In above code we are,

  • Displaying Flyout
  • Attaching change event on sports option list. In this post Id of Sports option in Flyout div is seenario3TextColor
  • Attaching click event to button and on click showing Flyout.
  • Displaying selected sports in output div

If you run, on the click event of button you should get Flyout to choose the sports as below,

image

I hope this post is useful. Thanks for reading

 

List View Data Binding in Windows 8 JavaScript Metro Application

In this post we will see,

  1. Working with ListView control in WinJS
  2. ItemTemplte in WinJS
  3. Data Binding to ListView
  4. Creating Data Source in WinJS

For purpose of this post I am going to bind name and images of Indian cricket player in ListView. After data binding ListView should look like below,

image

To bind data with ListView you need to follow certain steps.

  1. Create a Data Source
  2. Create ItemTemplate and bind data source properties to Html elements of ItemTemplate
  3. Create ListView and attach ItemTemplate to ListView
  4. Set the DataSource of ListView

Create Data Source

Let us create data to bind to the List View. I have given name of the array as PlayerData. This contains two objects Name and Photo.


var PlayerData = [
{ Name: 'Sachin Tendulkar', Photo: 'images/ST.jpg' },
{ Name: 'Mahender Singh Dhoni', Photo: 'images/MSD.jpg' },
{ Name: 'Saurabh Ganguli', Photo: 'images/SG.jpg' },
{ Name: 'Harbhajan Singh', Photo: 'images/HS.jpg' },
{ Name: 'Youvrah Singh', Photo: 'images/YS.jpg' },
{ Name: 'VVS Laxman', Photo: 'images/VVS.jpg' },
{ Name: 'Virendar Shewag', Photo: 'images/VS.jpg' },
{ Name: 'Zaheer Khan', Photo: 'images/ZK.jpg' },
{ Name: 'Sachin Tendulkar', Photo: 'images/ST.jpg' },
{ Name: 'Mahender Singh Dhoni', Photo: 'images/MSD.jpg' },
{ Name: 'Saurabh Ganguli', Photo: 'images/SG.jpg' },
{ Name: 'Harbhajan Singh', Photo: 'images/HS.jpg' },
{ Name: 'Youvrah Singh', Photo: 'images/YS.jpg' },
{ Name: 'VVS Laxman', Photo: 'images/VVS.jpg' },
{ Name: 'Virendar Shewag', Photo: 'images/VS.jpg' },
{ Name: 'Zaheer Khan', Photo: 'images/ZK.jpg' }
];

To create Data Source, I have put all the images of players in image folder. In real time applications, data must be downloaded from the Service.

Create Item Template

We need to create ItemTemplate to bind with the ListView. There are few points you need to keep in mind while creating ItemTemplate

  • ItemTemplate is a div
  • To convert div as ItemTemplate div need to have attribute data-win-control set to WinJS.Binding.Template
  • Other HTML elements should be inside the template div tag.
  • Data-win-bind is used to bind data to HTML elements.

Below I have put one div to bind name of the player and image to bind image of the player.

image

Create ListView

Data has been created. ItemTemplate has been created. Next you need to create ListView and bind ItemTemplate to that ListView.

  • ListView is a div
  • data-win-control property of div should be set to WinJS.UI.ListView
  • data-win-options take complex values.
  • Value of itemRenderer should be set to id of the div created as ItemTemplate. In our case id of ItemTemplate div is playeritemtemplate. So value of itemRenderer should be playeritemtemplate.
  • Layout should be set.
  • Value of maximum rows can be set.

Below you can find, I have created ListView and bind it to the ItemTemplate.

image

Putting all together HTML should be as below. I have put an output div. Selected value from the ListView will be displayed in output div.

Default.html


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>DataBindingPlayer</title>
<!-- WinJS references -->
<link rel="stylesheet" href="/winjs/css/ui-dark.css" />
<script src="/winjs/js/base.js"></script>
<script src="/winjs/js/ui.js"></script>
<script src="/winjs/js/binding.js"></script>
<script src="/winjs/js/controls.js"></script>
<script src="/winjs/js/animations.js"></script>
<script src="/winjs/js/uicollections.js"></script>
<script src="/winjs/js/wwaapp.js"></script>

<!-- DataBindingPlayer references -->
<link rel="stylesheet" href="/css/default.css" />
<script src="/js/default.js"></script>
</head>
<body>
<h2>Indian Team</h2>
<br />

<div id="playeritemtemplate"
data-win-control="WinJS.Binding.Template">
<div data-win-bind="innerText:Name"
style="height:20px;">
</div>
<img data-win-bind="src:Photo"
style="width:200px;height:150px;"  />
</div>

<div id="PlayerListView"
data-win-control="WinJS.UI.ListView" style="height:185px;"
data-win-options="{itemRenderer:playeritemtemplate,layout:{type:WinJS.UI.GridLayout,maxRows:1}}" >
</div>

<br />
<div id="ouputDiv" >
<span>You Selected </span>
<span id="selectedPlayer" style="height:20px;" ></span> <br />
<img id="selectedPlayerImg" style="width:200px;height:150px;"/>
</div>
</body>
</html>

Binding Data Source to ListView

To bind ListView with data source, first you need to fetch ListView div and then simply set datasource value. Below I am fetching ListView div and then setting data source value to PlayerData. If you remember, I created PlayerData as data source in starting of this post.

image

Attaching event to ListView

As of now you have created ListView and bind data source to that. Next you may want to fetch the selected item. For that you need to attach iteminvoked event to the ListView. You can add that as below. In below SelectItem is a function and it will get called on the item selection

image

In SelectItem function you will have to fetch the value of selected item and set as value of HTML element of output div.

image

Putting all together js file will have below codes

Default.js


(function () {
'use strict';
// Uncomment the following line to enable first chance exceptions.
// Debug.enableFirstChanceException(true);


var PlayerData = [
{ Name: 'Sachin Tendulkar', Photo: 'images/ST.jpg' },
{ Name: 'Mahender Singh Dhoni', Photo: 'images/MSD.jpg' },
{ Name: 'Saurabh Ganguli', Photo: 'images/SG.jpg' },
{ Name: 'Harbhajan Singh', Photo: 'images/HS.jpg' },
{ Name: 'Youvrah Singh', Photo: 'images/YS.jpg' },
{ Name: 'VVS Laxman', Photo: 'images/VVS.jpg' },
{ Name: 'Virendar Shewag', Photo: 'images/VS.jpg' },
{ Name: 'Zaheer Khan', Photo: 'images/ZK.jpg' },
{ Name: 'Sachin Tendulkar', Photo: 'images/ST.jpg' },
{ Name: 'Mahender Singh Dhoni', Photo: 'images/MSD.jpg' },
{ Name: 'Saurabh Ganguli', Photo: 'images/SG.jpg' },
{ Name: 'Harbhajan Singh', Photo: 'images/HS.jpg' },
{ Name: 'Youvrah Singh', Photo: 'images/YS.jpg' },
{ Name: 'VVS Laxman', Photo: 'images/VVS.jpg' },
{ Name: 'Virendar Shewag', Photo: 'images/VS.jpg' },
{ Name: 'Zaheer Khan', Photo: 'images/ZK.jpg' }
];

WinJS.Application.onmainwindowactivated = function (e) {
if (e.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
WinJS.UI.processAll().then(function () {
var PlayerList = document.getElementById('PlayerListView').winControl;
PlayerList.dataSource = PlayerData;
PlayerList.addEventListener('iteminvoked', SelectItem);
});

}
}

function SelectItem(e) {
var selectedItem = PlayerData[e.detail.itemIndex];
var selecteplayer = document.getElementById('selectedPlayer');
selecteplayer.innerText = selectedItem.Name;
var selecteplayerImg = document.getElementById('selectedPlayerImg');
selecteplayerImg.src = selectedItem.Photo;
}


WinJS.Application.start();
})();



On running you should get ListView bind with players name and image.

image

I hope this post is useful. Thanks for reading.

Working with JavaScript in Silverlight 4.0

In this post I will show you calling of Javascript function from Silverlight. It is very simple and straight forward.

Assume you have a JavaScript function on aspx page as below,

SilverlightTestPage.aspx


<script type="text/javascript" language="javascript" >
         function callmeonPageLoad() {
             alert("Hello Javascript from Silvertlight");
         }
    </script>


You want to call this Javascript function on page load of the Silverlight page then you will have to add namespace

clip_image001

And in the constructor of the page call it as below,

MainPage.xaml.cs


using System.Windows.Controls;
using System.Windows.Browser;

namespace SilverlightApplication7
{
   [ScriptableType]
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            HtmlPage.RegisterScriptableObject("MainPage", this);
            HtmlPage.Window.Invoke("callmeonPageLoad");

        }
    }
}


If you notice above code you would find that MainPage is attributed with ScriptableType.

clip_image002

On running Silverlight application you will be getting output as below,

clip_image004

On your XAML if you have textbox like below,

clip_image005

You want to access and change value of textbox txtName in Javascript then it too is very simple. Create a function Javascript as below,

SilverlightTestPage.aspx


 <script type="text/javascript">
        function UpdatingTextBoxValue(sender)
        {

            var txtBlockFromSL = sender.FindName("txtName");
            alert(txtBlockFromSL.text);
            txtBlockFromSL.Text = "Salsa ";
            alert(txtBlockFromSL.Text);


        }
</script>



txtName is name of the Silverlight text box.

And on the page load on aspx page add a param

clip_image001[5]

If you have a function in managed code and you want to access that from javacript .Assume you have function as below,

MainPage.xaml.cs



  [ScriptableMember]
       public void SilverLightFunction(string txtToUPdate)
        {
            txtName.Text = txtToUPdate;
        }





You can call this function from JavaScript as below,


 <script type="text/javascript">
        function UpdatingTextBoxValue(sender)
        {


            var host = sender.GetHost();
            host.content.MainPage.SilverLightFunction("Dhananjay");


        }
</script>



This was all about various ways to work with Silverlight and JavaScript. I hope this post was useful. Thanks for reading.