Angular2 is providing ngStyle to set CSS dynamically as like Angular1, but syntax is different. We can assign CSS element  by using JavaScript element.

Using ngStyle

Observe below highlighted code. [] represents one way binding
<button (click)="myStyle={color:'red'}">Set Color</button>
<button (click)="myStyle={'background-color':'blue'}">Set Background color</button>
<button (click)="myStyle = {}">clear</button>
<div [ngStyle]="myStyle">Click above button to set text color</div>
View DEMO

Using element style property

Observe below code. Here style.width was bound to myStyleWidth
<div [style.width.px]="myStyleWidth" [style.border]="myBorderStyle">
  sample text in div
</div>
Div Width :: <input [(ngModel)]="myStyleWidth"/>
border style :: <input [(ngModel)]="myBorderStyle"/>
View DEMO
Read More
Angular1 provides angular.element by to create JavaScript element. In Angular2, It is much easy, you can define element by using #<element name> as attribute

Markup to define element

<div #myElement>
  sample text in div
</div>

Emptying Element

You can empty element by using making whole inner HTML as null. Find below markup
<button (click)="myElement.innerHTML = ''">Empty div</button>

Remove Element

You can remove element by using .remove()
<button (click)="myElement.remove()">Empty div</button>
View DEMO
Read More
Angular2 is providing [attr.<attribute name>] to bind attribute values. Here it is

Markup :

Observe below code, role attribute was bound to roleVal 
<div id="divID" [attr.role]="roleVal">
  This text color can be changed by class
</div>

Angular Component Code

Observe below functions addAttr, removeAttr, checkAttr
(function(app) {
  app.AppComponent = ng.core
    .Component({
      selector: 'my-app',
      templateUrl: 'attr1_template.html'
    })
    .Class({
      constructor: function() {
        this.roleVal = '';
      },
      
      addAttr:function() {
        this.roleVal = 'admin';
      },
      
      removeAttr:function() {
        this.roleVal = '';
      },
      checkAttr:function() {
        alert(this.roleVal);
      }
    });

  document.addEventListener('DOMContentLoaded', function() {
    ng.platform.browser.bootstrap(app.AppComponent);
  });
})(window.app || (window.app = {}));
Read More
Angular2 is proving and ngClass directive as like Angular1. We can manipulate classes using this ngClass

Steps to add class using ngClass : 

  1. Initiate this.myClass to array
  2. Push classes into above array
this.myClass = [];
this.myClass.push('red');

Steps to remove class using ngClass : 

  1. Initiate $scope.myClass to array
  2. Pop classes from above array
this.myClass = [];
this.myClass.pop('red');

Steps to check class using ngClass : 

  1. Initiate this.myClass to array
  2. Check index of the class that you want to check
this.myClass = ['red'];
if(this.myClass.indexOf('red') == -1) {
    alert('false');
} else {
    alert('true');
}

Code for ngClass with Array

(function(app) {
  
  app.AppComponent = ng.core
    .Component({
      selector: 'my-app',
      templateUrl: 'ngClass_template.html'
    })
    .Class({
      constructor: function() {
        this.myClass = [];
      },
      
      addClass:function() {
        this.myClass.push('red');
      },
      
      removeClass:function() {
        this.myClass.pop('red');
      },
      
      checkClass:function() {
        if(this.myClass.indexOf('red') == -1) {
           alert('false');
        } else {
           alert('true');
        }
      }
    });

  
  document.addEventListener('DOMContentLoaded', function() {
    ng.platform.browser.bootstrap(app.AppComponent);
  });

})(window.app || (window.app = {}));
View DEMO

Steps to add class using ngClass with JSON

  1. Initiate this.myClass to JSON object of classes and boolean values
  2. Assign true for the JSON class name, that you want to add
this.myClass = {red:false};
addClass : function() {
   this.myClass.red = true;
}

Steps to remove class using ngClass with JSON

  1. Initiate $scope.myClass to JSON object of classes and boolean values
  2. Assign false for the JSON class name, that you want to remove
this.myClass = {red:false};
removeClass : function() {
    this.myClass.red = false;
}

Steps to toggle class using ngClass with JSON

  1. Initiate $scope.myClass to JSON object of classes and boolean values
  2. Assign opposite boolean value to the JSON class name
this.myClass = {red:false};
toggleClass : function() {
     this.myClass.red = !this.myClass.red;
};

Code for ngClass with JSON

(function(app) {
  
  app.AppComponent = ng.core
    .Component({
      selector: 'my-app',
      templateUrl: 'ngClass_template1.html'
    })
    .Class({
      constructor: function() {
          this.myClass = {red:false};
      },
      
      addClass:function() {
          this.myClass.red = true;
      },
      
      removeClass:function() {
          this.myClass.red = false;
      },
      
      toggleClass:function() {
          this.myClass.red = !this.myClass.red;
      },
      
      checkClass:function() {
          alert(this.myClass.red);
      }
    });
  
  
  
  document.addEventListener('DOMContentLoaded', function() {
    ng.platform.browser.bootstrap(app.AppComponent);
  });
})(window.app || (window.app = {}));
View DEMO

By Using [Class.]

Angular 2 is providing one way binding for classes with [class.<class name>]. It binds the presence of the CSS class red on the element to the truthiness of the expression redClassBool. Observe the below code
<div id="divID" [class.red]="redClassBool">
  This text color can be changed by class
</div>

Add Class

Assign true to this.redClassBool

Remove Class

Assign  false to this.redClassBool

Code for [class.] binding

(function(app) {
  
  app.AppComponent = ng.core
    .Component({
      selector: 'my-app',
      templateUrl: 'withCssClass_template1.html'
    })
    .Class({
      constructor: function() {
        this.redClassBool = false;
      },
      
      addClass:function() {
        this.redClassBool = true;
      },
      
      removeClass:function() {
        this.redClassBool = false;
      },
      
      toggleClass:function() {
        this.redClassBool = !this.redClassBool;
      },
      
      checkClass:function() {
        alert(this.redClassBool);
      }
    });
  
  
  
  document.addEventListener('DOMContentLoaded', function() {
    ng.platform.browser.bootstrap(app.AppComponent);
  });
})(window.app || (window.app = {}));
View DEMO
Read More
Here I have created AngularJS directive for setting and getting scroll position of an IFrame. Two way binding was applied here. Observe below markup.
Note : This directive wont work for cross domain iframes sources (For security reasons, browsers won't allow this)

Markup

Observe ng-iframe-scroll attribute. This is the main directive. ng-iframe-scroll-x, ng-iframe-scroll-y are supporting  directives. ng-iframe-scroll-x will bind to X-axix scroll positions. ng-iframe-scroll-y will bind to Y-axix scroll positions
<iframe src="myFrame.html" ng-iframe-scroll ng-iframe-scroll-x="xval" ng-iframe-scroll-y="yval"></iframe>

Script

Observe below code for directive
angular.module('myApp', []).controller('MyController', [ '$scope', function($scope) {
    $scope.iFrameScroll = {x:10,y:1000};
}]).directive('ngIframeScroll', function(){
     return {
           restrict : "A",
           scope : {sx:'=ngIframeScrollX', sy:'=ngIframeScrollY'},
           link : function(scope, element, attrs) {
              var y;
              var x;

              element.bind("load", function(event) {
                  this.contentWindow.onscroll = function (e) {
                     x = this.pageXOffset;
                     y = this.pageYOffset;
                     setValues();
                  };
                  scrollIt();
                 });
              
              scope.$watch('sy', function(val){
                  y = val;
                  scrollIt();
              });
              
              scope.$watch('sx', function(val){
                  x = val;
                  scrollIt();
              });
              
              function scrollIt() {
                  var doc = (element[0].contentWindow || element.contentDocument);
                  doc.scrollTo(x, y);
              }
              
              function setValues() {
                  scope.sx = x;
                  scope.sy = y;  
                  scope.$apply();
              }
           }
        };
});
Read More
Its very easy. The AngularJS beginners  might be curious on this. $scope is also an object. So $scope variables represents key value pairs of Javascript object. Here I have given one simple example to show to do this

For $scope variables

$scope.val1 = "object value 1";
$scope.val2 = "object value 2";

$scope['val1'] // gives 'object value 1'
$scope['val2'] // gives 'object value 2'

For JavaScript variables 

We can use eval to find local JavaScript variables within a function
var jsvar = "object variable";
eval('jsvar') // gives 'object variable'

For JavaScript Global Variables

Here it is JavaScript global variables. these are part of window object.
var globalJsvar = "global variable";
function myCtrl($scope) {
  window['globalJsvar'] // gives 'global variable'
}
Read More
This example is about listing all functions and objects in $scope. $scope is also one Javascript object. By listing key value pairs of $scope, we can list down all functions and objects.

Example Code

Here functionArray, varArray arrays are variables and fun1 is function. We have to list them in same types.
$scope.functionArray = [];
$scope.varArray = []; 
$scope.fun1 = function() {  
};

Code to List Down Functions And Variables

Here key represents name of variable or function. We can verify functions with angular.isFunction and objects or variables with angular.isObject 
$scope.listFunAndVar = function() {
    var obj = $scope;
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (angular.isFunction(obj[key])) {
                $scope.functionArray.push(key);
            } else if (angular.isObject(obj[key])) {
                $scope.varArray.push(key);
            }
        }
    }

};

Default $scope objects

AngularJS defines some objects to $scope. Those are "this","$$listeners","$$listenerCount","$parent","$$watchers"
Read More
By applying this filter, you can generate N C K combinations. N is length of the array. K is number of elements to be in set of combination. User has to give K value

Markup

myArray is array
combinate is filter name
2 is K value
<div ng-repeat="val in myArray | combinate:2">{{val}}</div>

Script

iArray is the input array
kval is the K value
combinate is filter name
angular.module('myApp', []).filter('combinate', function() {
    return function(iArray, kval) {
        var n = iArray.length;
        function combine(k) {
            var result = [];
         
            //illegal case
            if (k > n) {
                return null;
            //if k==n
            } else if (k == n) {
                var temp = [];
                for (var i = 0; i < n; i++) {
                    temp.push(iArray[i]);
                }
                result.push(temp);
                return result;
            //if k==1
            } else if (k == 1) {
         
                for (var i = 0; i < n; i++) {
                    var temp = [];
                    temp.push(iArray[i]);
                    result.push(temp);
                }
         
                return result;
            }
         
            //for normal cases, initialize a list with one element
            for (var i = 0; i < n - k + 1; i++) {
                var temp = [];
                temp.push(iArray[i]);
                result.push(temp);
            }

            
            return combineHelper(k, result);
        }
         
        function combineHelper(k, result) {
            
            var prevResult = result.slice();
         
            if(result[0].length == k) return result;
         
            result = [];
            for (var j=0; j<prevResult.length; j++) {
                    var one = prevResult[j];
                for (var i = j + 1; i < n; i++) {
                    var temp = one.slice();
                    temp.push(iArray[i]);
                    result.push(temp);
                }
            }
         
            return combineHelper(k, result);
        }
        return combine(parseInt(kval));
    };
}).controller('MyController', [ '$scope', function($scope) {
    $scope.myArray = [1,2,3,4,5];
} ]);
Read More
This filter will take array as input and generates all permutations to that array. Observe below markup

Markup

Here myArray is Javascript array, permute is filter
<div ng-repeat="val in myArray | permute">{{val}}</div>

AngularJS Code

This permute filter generates all permutations of given array and gives them as output
angular.module('myApp', []).filter('permute', function() {
    return function(num) {
        var result = [];
        //start from an empty list
        result.push([]);

        for (var i = 0; i < num.length; i++) {
            //list of list in current iteration of the array num
            var current = [];

            for (var k = 0; k < result.length; k++) {
                var l = result[k];
                // # of locations to insert is largest index + 1
                for (var j = 0; j < l.length + 1; j++) {
                    // + add num[i] to different locations
                    l.splice(j, 0, num[i]);

                    var temp = JSON.parse(JSON.stringify(l));
                    current.push(temp);

                    // - remove num[i] add
                    l.splice(j, 1);
                }
            }

            result = JSON.parse(JSON.stringify(current));
        }
        return result;
    };
}).controller('MyController', [ '$scope', function($scope) {
    $scope.myArray = [1,2,3,4,5];
} ]);
Read More

Blogroll


Follow this blog by Email

Popular Posts