Simplifying Two-Way Data Binding in Angular 2

There are three types of data bindings in Angular 2, they are as follows:

  1. Interpolation
  2. Event Binding
  3. Property Binding

If you are coming from Angular 1.X background, you might be wondering that where is the two-way data binding? Remember, when first time you saw AngularJS 1.X demo, and was just blown away by power of ng-model? Yes, like you, I was also very impressed by power of two-way data binding in AngularJS 1. Even though, AngularJS 1 two-way data binding was beautiful, it came with the baggage of digest cycle and $watch.

To simplify the things, Angular 2 does not have any built in Two-Way data binding. It does not mean; you cannot have two-way data binding in Angular 2 application. Come on, we cannot think of creating a modern web application without having power of two-way data binding. So, in this post, we are going to learn, how to work with two-way data binding in Angular 2.

image

Two-way data binding with ngModel

Angular 2 provides us a directive ngModel to achieve two-way data binding. It is very simple and straight forward to use ngModel directive as shown in the listing below:

To use ngModel directive, we need to import FormsModule in the application. For your reference, below I am listing app.module.ts which is importing FormsModule besides other required modules.

In above demo, when typing into the input element, the input’s value will be assigned to name variable and also it would be displayed back to the view. So we are implementing two-way data binding using ngModel as shown in the below image:

image

Two-way data binding without ngModel

To understand ngModel directive working, let us see how we can achieve two-way data binding without using ngModel directive. To do that, we need to use

  1. Property binding to bind expression to value property of the input element. In this demo, we are binding name variable expression to value property.
  2. Event binding to emit input event on the input element. Yes, there is an input event which will be fired whenever user will input to the input element. Using event binding, input event would be bind to an expression.

So, using the property binding and the event binding, two-way data binding can be achieved as shown in the listing below:

Same like ngModel directive demo in this demo also, when typing into the input element, the input element’s value will be assigned to name variable and also it would be displayed back to the view.

So we are implementing two-way data binding without using ngModel using the code shown in the below image:

image

Let us understand few important things here:

  1. [value]=”name” is the property binding. We are binding value property of the input element with variable (or expression) name.
  2. (input)= “expression” is event binding. Whenever input event will be fired expression will be executed.
  3. “name=$event.target.value” is an expression which assigns entered value to name variable.
  4. Name variable can be accessed inside AppComponent class.

So far we have seen two-way data binding using ngModel and without ngModel. We can conclude that the directive ngModel is nothing but combination of property binding and event binding. Event binding is denoted using small bracket and property binding is denoted using square [] bracket, and if you notice syntax of ngModel is [(ngModel)], which is like a banana put into a box suggests it is combination of both event and property binding.

image

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

How to Create a YouTube AngularJS Directive

I have often seen, developers come across requirement to embed a YouTube video in an AngularJS application. In this post, we will learn to create a simple YouTube AngularJS directive and also to use some of the popular directive from the GitHub.
We will follow step by step approach to create the YouTube custom directive. So let us start with create module and the controller.

var myApp = angular.module('myApp', []);
myApp.controller('VideoController', function ($scope) {
    $scope.video = 'zRtPUIumXcY';
});

Next we will create a custom directive with the isolated scope. Let us go ahead and create YouTube directive with following characteristics

  • Directive will be used as an Element
  • Directive will work in the isolated scope
  • Directive replace property is set to true, such that user will not able to view the directive information in the browser
  • In the template, iframe is used to play the YouTube video.
  • In the link function, we are watching the object passed to directive. Whenever value of object changed, directive will play the different video from the YouTube.

By putting all above together, directive is created as shown in the listing below:


myApp.directive('angularYoutube', function ($sce) {
    return {
        restrict: 'E',
        scope: { video: '=' },
        replace: true,
        template: '<div style="height:300px;"><iframe style="overflow:hidden;height:100%;width:100%" width="100%" height="100%" src="{{url}}" frameborder="1" allowfullscreen></iframe></div>',
        link: function (scope) {
            scope.$watch('video', function (newVal) {
                if (newVal) {
                    scope.url = $sce.trustAsResourceUrl("http://www.youtube.com/embed/" + newVal);
                }
            });
        }
    }
})

As you might notice in above listing that in the template, we are using the iframe to play the YouTube video. Also we are watching the value passed to the directive and constructing the URL using the $sce service of AngularJS.
On the view, angularYoutube directive can be used as shown in the listing below:

<div ng-controller="VideoController">
        <angular-youtube video="video"></angular-youtube>
    </div>

As of now, we should able to play a video in AngularJS application. Right now we are passing hard coded video code from the controller. We can allow user to pass the video code, just by using an input textbox as shown in the listing below:


<div ng-controller="VideoController">
        <input type="text" ng-model="video" placeholder="enter video code here to play"/>
        <hr/>
        <angular-youtube video="video"></angular-youtube>
    </div>


Here we have created a very simple custom AngularJS directive to embed the YouTube video in the AngularJS application.
For advanced scenarios, you may want to use Angular YouTube Embed . I find it very useful for advanced scenarios. I hope you find this post useful. Thanks for reading.

How to create Custom Filters in AngularJS

Have you ever used filters with the ng-repeat directive as shown in the listing below?

image

If so, then you’ve used a filter in an AngularJS application. AngularJS provides us many in-built directives like search. If required, AngularJS also allows us to create custom filters, which we’ll explore in this post.

AngularJS gives us a simple API to create a custom filter. You’ll remember that we use app.controller() to create controllers and app.module() to create modules. In exactly the same way, AngularJS has given us the angular.filter API to create a custom filter in AngularJS.

A custom filter can be created using the following syntax:

image

Read full article on the Infragistics blog

How to work with the Ignite UI Chart in an AngularJS application

In this post we will learn how to work with the Ignite UI chart in an AngularJS application. Although I will use the ASP.NET Web API to pull data from the database, you can use REST service or a Web API created on any stack with the Ignite UI charts in your AngularJS application. This article is divided in two sections:

  1. Section 1 : creating ASP.NET Web API using Code First approach
  2. Section 2 : using Ignite UI in AngularJS application

If you already have or know how to create the Web API REST Service (Note: from here on out in this post, we’ll use the term “Web API” to refer both to REST Service and Web API), you can jump to section 2 of this article. On the other hand if you need help in how to create ASP.NET Web API start from the section 1. Here’s a high level flow of diagram of an application::

image

Read full article on the Infragistics blog

Validating User Input on a Form in Angular JS

I have often seen entry level developers struggling with user input validation in AngularJS single page applications. In this post, I will give a quick but useful introduction of validations in AngularJS; consider this post as a base learning document from which you can do further learning.

Let’s start with an example as shown in the image below. You have a registration form with three fields with the following restrictions.

  1. Name : Required
  2. Email : Required and type Email
  3. Password : Required , type password and minimum length 6

We want to validate the rules mentioned above at the client side. There are two ways client side validation can be done in an AngularJS based single page application:

  1. Using the HTML5 validations
  2. Using the AngularJS validation directives
  3. A Combination of both

HTML5 validation

Here we’ve created the Add user form shown above using the mark up listed below:

image

Read full article on the Infragistics blog

Hosted workshop on SPA using AngularJS for BirlaSoft

On Saturday 18th July, for Infragistics, I delivered a workshop on Single Page Application using AngularJS for BirlaSoft . A special thanks to C-SharpCorner Delhi Chapter for arranging the workshop.

clip_image002

5 Hrs. long workshop was attended by around 45 engineers. We learnt about the following topics,

  • Introduction of AngularJS
  • Controller and $scope
  • Views and Routing in AngularJS
  • Directives
  • ASP.NET Web API
  • CORS in Web API
  • Ignite UI with AngularJS

We were mange to create an end to end AngularJS based Single Page application performing CRUD operation using the ASP.NET Web API.

Audience participations was highly energetic and some of their feedback are motivating for us. One of such feedback is below:

clip_image002[6]

clip_image003

Overall it was productive Saturday for all of us and I personally had fun time teaching engineers of BirlaSoft.

clip_image005

Once again big thank you to Infragistics and C# Corner Delhi chapter for the opportunity. If you are interested in such workshop for your organization, feel free to reach us.

Exploring Angular’s “Controller as” Syntax and the vm Variable

Read full article on the Infragistics blog

Often, I hear developers ask “What is the ‘controller as’ syntax and how it is different from the $scope object approach of controller creation?” In this post we will learn about controller as syntax and compare it with the $scope object approach of controller creation.

In AngularJS 1.2, the “controller as” syntax was introduced, and made controller code creation more readable. Let’s see both approaches in action below:

Creating a controller using the $scope object

Usually we create a controller using the $scope object as shown in the listing below:

image

Above we are creating the AddController with three variables and one behaviour, using the $scope object controller and view, which talk to each other. The $scope object is used to pass data and behaviour to the view. It glues the view and controller together.

Essentially the $scope object performs the following tasks:

  1. Pass data from the controller to the view
  2. Pass behaviour from the controller to the view
  3. Glues the controller and view together
  4. The $scope object gets modified when a view changes and a view gets modified when the properties of the $scope object change

We attach properties to a $scope object to pass data and behaviour to the view. Before using the $scope object in the controller, we need to pass it in the controller function as dependencies.

Using the “controller as” syntax and vm

We can rewrite the above controller using the controller as syntax and the vm variable as shown in the listing below:

image

Read full article on the Infragistics blog

Understanding scopes in AngularJS custom Directives

Read full article on the Infragistics blog

In this post we will learn about different kinds of scopes in AngularJS custom directives. First we’ll start with a high level introduction of directives and then focus on scopes.

Directives

Directives are one of the most important components of AngularJS 1.X, and have the following purposes:

  1. Gives special meaning to the existing element
  2. Creates a new element
  3. Manipulates the DOM

Mainly, directives perform either of the following tasks:

Manipulate DOM

  • Iterate through data
  • Handle events
  • Modify CSS
  • Validate data
  • Data Binding

Even though there are many built-in directives provided by the Angular team, there are times when you might need to create your own custom directives. A custom directive can be created either as an element, attribute, comment or class. In this post, a very simple custom directive can be created as shown in the listing below:

image

While creating custom directives, it’s important to remember:

  • The directive name must be in the camel case;
  • On the view, the directive can be used by separating the camel case name by using a dash, colon, underscore, or a combination of these.

Scopes in Custom Directives

Scopes enter the scene when we pass data to custom directives. There are three types of scopes:

  1. Shared scope
  2. Inherited scope
  3. Isolated scope

Read full article on the Infragistics blog