Category: AngularJS

Angular Change Detection

Easy way to understand change detection in angular with example

Angular’s change detection is a mechanism that allows the framework to automatically detect and update the view whenever there is a change in the application data. It’s a core part of Angular’s functionality that enables the framework to maintain a reactive and interactive user interface.

Angular’s change detection system operates by comparing the current and previous states of the application data. When there is a change in the data, the change detection mechanism triggers a re-evaluation of the view, updating it with the new data.

Angular offers two modes of change detection: default and OnPush. The default change detection mode checks for changes in all component properties and their nested properties. In contrast, the OnPush mode is an optimization technique that limits the change detection to the components with an @Input decorator, or that use immutable objects and observables.

The change detection process can be triggered in three ways:

  1. Default change detection: This is the default change detection strategy used by Angular. In this strategy, Angular checks for changes to the component’s properties and inputs on every change detection cycle. This can be resource-intensive and can slow down the application in large and complex applications. Here’s an example:

In the above code, the CounterComponent has a count property that is incremented every time the increment method is called. Since the default change detection strategy is used, Angular will detect and update the view on every change detection cycle.

OnPush change detection: The OnPush change detection strategy is an optimization that can improve the performance of an application by reducing the number of change detection cycles. In this strategy, Angular only checks for changes to the component’s inputs and properties if the reference to the input or property has changed. Here’s an example:

Manually triggering change detection: This can be achieved by calling the ChangeDetectorRef.detectChanges() method in the component code.

In this above example, we are using the push strategy that means CheckOnce, rather than the default CheckAlways, then forces a second check after an interval

In Angular, we can manually trigger change detection using the detectChanges() method of the ChangeDetectorRef service. The ChangeDetectorRef service is available in every Angular component and provides several methods for manually triggering change detection:

  • detectChanges(): This method triggers a change detection cycle for the component and its children.
  • markForCheck(): This method marks the component and its children for change detection but doesn’t trigger a change detection cycle immediately. Angular will trigger change detection during the next change detection cycle.
  • detach(): This method detaches the component from the change detection tree, preventing it from being checked for changes. This can be useful when we have a component that doesn’t need to be updated frequently.
  • reattach(): This method reattaches the component to the change detection tree, allowing it to be checked for changes again.

Here’s an example of manually triggering change detection:

In the above code, the MyComponent retrieves items from a DataService asynchronously and displays them in a list. When the user clicks the “Add Item” button, we add a new item to the list and mark the component for change detection using the markForCheck() method.

In summary, we can manually trigger change detection in Angular using the detectChanges() method of the ChangeDetectorRef service. Additionally, the markForCheck(), detach(), and reattach() methods provide additional flexibility for controlling when change detection is triggered.

It’s worth noting that Angular’s change detection mechanism is highly performant, thanks to its ability to detect only the changes that occur in the application data. However, it’s important to be mindful of the number of components that are being checked for changes, as this can impact the performance of the application. In some cases, optimizing the change detection strategy can lead to significant performance gains in large applications.

Most popular JavaScript frameworks in 2016

In this modern web JavaScript is the most popular language in the web to building the web application. There are many different ways to build modern web application with JavaScript, including a lot of different tool choices, and a lot of new theory to learn.Using the JavaScript we can easily extend the functionalities and logical executions of the component.

Most of the developer are used JQuery along with JavaScript to extend the features of HTML component,but when we talk about the large application it requires more effort and complex in code to develop and the maintain a large application. JavaScript Frameworks help to build fast,interactive and scalable web applications (which includes both single page and multiple page applications).

But, unfortunately! Most programmers find it hard to decide which framework they use and learn. Thus, in this article, I am going to highlight the 7 most popular JavaScript Frameworks in 2016. Let’s get started!

2016-most-popular-framework

7 most popular JavaScript Frameworks in 2016

1. AngularJS

When we talked about javascript frameworks the first word comes in our mind is that AngularJS. AngularJS, as this is the most commonly used JavaScript Framework by javascript developers. It released in 2009, javaScript based open-source front-end framework to create web application or SPA (Single page application) mainly maintained by Google.

It supports the MVC (Model–view–controller),MVVM (Modal-view-ViewModal) and MVW (Modal-View-Whatever) design paradigm which supports standard two-way data binding. In MVW, whatever stands for “whatever works for you”. Angular gives you the lot of flexibility to separate presentation logic from business logic and presentation state. In MVC, your data is updated on both the UI (presentation state) and back-end (coding or server side) whenever it detects some changes in the engine.

As the UI components (View) are separated from the Model components, you can easily build reusable components for amazing and user-interfaces!

Recently Angular 2.0 has been released in OCT 2016, which claims to improve the speed & performance of mobile and desktop and take it further via web workers and server-side rendering. Meet huge data requirements by building data models on RxJS, Immutable.js or another push-model. Angular Loved by Millions of developers across the globe and it’s highly recommended for anyone who wants a powerful MVC framework with a strong and modern infrastructure that takes care of everything for you to build single page applications.

Angular is also planning to release Angular 4.0 then it called ‘Angular’

Video: See the announcement yourself

(Note: This is my personal favorite JavaScript Framework till date)

2. React

React (sometimes styled React.js or ReactJS) is an open-source JavaScript library which provides a view for data rendered as HTML. Components have been used typically to render React views which contain additional components specified as custom HTML tags. React gives you a trivial virtual DOM, powerful views without templates, unidirectional data flow and explicit mutation. It is very methodical in updating the HTML document when data changes; and a clean separation between components on a modern single-page application. React also support sever-side rendering with with nodejs

As your app comes into existence and develops, it’s advantageous to ensure that your components are used in right manner and React app consists of Reusable components, which makes code reuse, testing, and separation of concerns easy.

ReactJS is not only “V” in MVC, it has stateful components, it handles mapping from input to state changes, and it renders components. I would highly recommend this Framework if you just need a front-end development Framework to build an incredibly complex and awesome UI through the power View Layers. In this sense, it does everything that an MVC does.

Apart from Facebook and Instagram, there are several companies that use React, including Whatsapp, BBC, PayPal, Netflix, Dropbox, etc.

3. Ember

Ember.js is open-source javascript frameworks like angular and react. Initially it released in 2011, 5 year ago. It has a huge active community online, so whenever  you face any problem, you can ask them.

Ember.js is based on Model–view–viewmodel (MVVM) design pattern, which is slightly different than MVC, In the sense that the view model is more than view and handles most if not all of the view’s display logic

For the fast server-side rendering with nodejs and adding  the animation in UI. we need to use Ember CLI addon Fastboot.js and liquid-fire.js, so the applications have extremely enhanced performance of complex UI with animation.

Ember supports Handlebars integrated templates that update the data changes automatically. It also provides routes, dependency injection, declarative two-way data binding and Custom components.

In 2015, Ember was best JavaScript Framework, competing against AngularJS and React, which should be enough to convince you about its usability and desirability in the JavaScript framework,there are several big companies who’s using ember.js Yahoo!, Zendesk, GROUPON, Yapp, MHElabs, TILDE.

I have not worked much in ember.js but as per my knowledge i would highly recommended this JavaScript Framework to those who don’t necessarily need great flexibility or a large infrastructure, and just prefer to get things done for coping with deadlines.

4. Knockout.js

This JavaScript framework was initially released by Steve Sanderson in 2010 as open source under MIT license. Knockout works under the MVVM design paradigm and that makes it a little different from Ember and Angular.

Knockout has no dependencies on any other libraries and it supports all mainstream browsers like IE 6+, Firefox 3.5+, Chrome, Opera, Safari (desktop/mobile) it’s not popular as much competitors like Angular, Ember or Backbone. The slow growth is simply because of improvements and adding more features in framework.

Developer community is slowly moving to frameworks like React and Angular. Knockout has a great capability and can definitely make a come back but only if someone else adopts it and starts improvement it with the latest web JavaScript technologies.

You can read more about Knockout at knockoutjs.com.

5. Meteor.js

If you LOVE developing the website in pure javascript then MeteorJS is for you. It’s the full stack platform for building modern end to end mobile and web applications completely in JavaScript, for all environments: Application server, Web browser, and Mobile device.

Meteor is the child of Meteor Development Group, it was first released in 2012 as an open source JavaScript framework under MIT license.

Ever since its release, the MeteorJS community too is vibrant and helpful. You would find tons of resources, tutorials and custom packages that give super powers to solve your development errors and develop your app in MeteorJS.

The best thing about MeteorJS is that you use only JavaScript for front-end and backend application development, no need to invest time learning anything else.

The server side packages run in the node.js and you do not need do anything else but MeteorJS packages to access the database, all in JavaScript, this makes developer life easy for building real time web applications.

From Performance perspective, any changes in the database are reflected back on the UI in the real time and vice versa without the handshake between different languages with minimal development efforts.

You can read more about Meteor at – meteor.com.

6. Vue.js

Vue.js is another open-source JavaScript framework was released in 2014. It supports extremely simple API for developing the Reactive components for Modern Web Interfaces Like Ember, it also uses the Model–view–viewmodel (MVVM) design paradigm which helpes in the simplification of the design.

The most important feature in this framework is that you can use selective modules with it for your specific needs. For example, you need to write HTML code, fetch the JSON and create a Vue instance to create the small effects that can reused!

Similar like others JavaScript Frameworks, it also uses two-way data binding to update the model and view, plus it also uses binder for communication between the view and data binder. If you thinking that is full-fledged framework to focus on it then I must say it’s not like what you thinking because it’s focuses entirely on the View Layer, so you would need to take care of other components on your own or you can use any other framework with them.

If you are familiar with AngularJS, then you will feel comfortable with this too, as it heavily incorporates the architecture of AngularJS, so many projects can be easily transferred to this Framework if you know the basics of JavaScript.

As I didn’t get chance to work with that but if you just want to get things done or gain JavaScript programming experience, or if you need to learn the nature of different JavaScript Frameworks you should try this.

7. Backbone.js

This framework can be easily integrated to any third-party template engine, however, by default it has dependancy on Underscore templates along with JQuery, It has the RESTful JSON interface with the support of MVC (Model–view–controller) design pattern.

If you ever heard or used the famous social news networking service reddit, then you will be interested to hear that it uses the Backbone.js for several of its single-page applications. Jeremy Ashkenas who developed the Backbone.js, it has also created the Underscore templates as well as CoffeScript, so you are assured that the developer knows his stuff.

This framework provides models with key-value, views and several modules within a single bundle, so you don’t need to download the other external packages, saving you time. The source-code is available on Github, which means you can further modify it for your needs. There are several big companies who’s using backbone.js 500px Web, Airbnb, Pinterest, Reddit, WordPress.com, USA Today.com,LinkedIn Mobile.

Conclusion

So, I have just highlighted the 7 most popular JavaScript Frameworks in this article in the hopes that it will help you choose the best JavaScript Framework for your tasks.

If you’re still having trouble to choose the best JavaScript Framework for your learning or build web application for your project, then please understand the project requirement and client expectations; and if it doesn’t then just try the next one. Rest assured though that any Framework from the list will be good enough.

The best way to learn code is to write code!!!

AngularJS Starter Templete With Bootstrap

If you have not tried yet to create angularjs website then definitely this article will help you to create angularjs website with bootstrap starter template. So let’s start.

In this example i am using bootstrap “Justified nav” template.

thumbnail

These are the following AngularJs features what we will covered with creating this template

  1. MVC(Model view Controller) Architecture
  2. Calling JSON service with factory
  3. Dependency Injection
  4. AngularUI Bootstrap
  5. Routing
  6. Directives
  7. Image Gallery with AngularJS

At the end of the article you understand what is MVC Architecture and how it works in AngularJS? | AngularJS MVC
MVC: It’s a design pattern that breaks the application into three parts Model View Controller. Using a pattern is a reusable solution but in regular javascript we organize the code differently. Another way of looking at patterns are as a templates which can be used in quite a few different scenarios.

Model:

Model is belongs to data it can be dynamic data or static which means you can get it from a database like Mongodb and you can also get data from static JSON file.

Let’s create a static JSON to defining a model. Add following lines in a data.json file.

View:

View is displaying the data of model. For this we use double curly brackets and it is lot like using JavaScript template library (like mustache.js).

Let’s create a view, following this instruction in index.html:

  • First declare the name of the application using ng-app directive.
  • Download and add the angular library in your page version – v1.3.0-rc.5.
  • Defining the controller name using ng-controller directive in your parent element.

    Let’s combined the code:

In this HTML we have use ng directives to rendering the data in view.

ng-repeat: The ngRepeat directive instantiates a template once per item from a  collection. Each template instance gets its own scope, where the given  loop variable is set to the current collection item, and $index is set to  the item index or key.

ng-init: The ngInit directive allows you to evaluate an expression in the current  scope.

ng-click: The ngClick directive allows you to specify custom behavior when an   element is clicked.

ng-show: The ngShow directive shows or hides the given HTML element based on    the expression provided to the ngShow attribute.

Controller

It controls how data is retrieved and displayed to end-user. which means Controller gives you control over model and view.

Creating angular module name which we have defined in ng-app directive in HTML.

We can also defined the dependency as per the module using [] brackets. For our application we need ngRoute for routing to navigate the site. For this you have to download and include

AngularUI Bootstrap “ui.bootstrap” using the angular bootstrap component., you can download the library from this link https://angular-ui.github.io. and add in html page.

Creating Factory in Angularjs

AngularJS provides you three ways to create a service : factory,service and provider. A factory is a simple function which allows you to add some logic before creating the object. It returns the created object.

Scope is the glue between application controller and the view. During the template linking phase the directives set up $watch expressions on the scope. The $watch allows the directives to be notified of property changes, which allows the directive to render the updated value to the DOM.

If you find AngularJS MVC Article helpful please share it and comment below.

You can get the full code from here: https://github.com/harmeet090/Angularjs

Getting started AngularJS with Liferay Portal

After reading the title of this post the first question comes in your mind is “Can we use AngularJS with Liferay?”
and my answer is yes we can. Now your thinking why AngularJS? I will give the answer of your all questions in this article.

What is AngularJS?

Angular js is open source web application development framework developed by Misko Hevery and maintained by Google. AngularJS architecture based on MVC(Model – View – Controller). MVC pattern help you to manage separately presentation, data, and logic components. server-side services are offered by Angular, like view-dependent controllers, to client-side web applications.

These are the some remarkable features:

  • HTML Declarative approach:This feature help you to declaring dynamic views in static web-applications. For your application, AngularJS facilitates you to extend HTML vocabulary. The consequential ssetting is especially expressive, readable, and quick to develop.
  • Easy Data Binding : AngularJS Two-way data binding is its most distinctive feature, and it reduces the amount of write dynamic code.
  • Reusable Components: Using AngularJS directives help you to make your component reusable.
  • Dependency Injection: You can easily inject dependencies of other modules in your web Application. Dependency injection is also a core to AngularJS.
  • End to end Integration Testing / Unit Testing: While writing a code for application, we also need write test cases. Angular is designed makes testing your application easy by using dependency Injection feature that makes testing components much easier then any other frameworks. Jasmine and Karma are the testing tool which we use in angular application
  • Routing: This feature allows to make your SPA website much easier.
  • Templating: Dynamically creating and updating HTML based on templates.
  • Services: you can use server side services in angular to make your web application dynamic.

If you are thinking to develop Angular Web Application in LIferay Developer Studio then Before starting to write a code you must know how to configure AngularJS in your liferay. It’s reduce your efforts to develop and maintain your Angular Web Application in Liferay. You can also write individual portlet in AngularJS. So in this article i am going to make a Independent News List portlet with the help of JSON Array in Angular.

Creating a liferay portlet

  • Go to the package Explorer > Right click New > Select Liferay Plugin Project

See Figure 1
Angular-porlet

If you want to setup AngularJS in Liferay developer studio. Read this article

or you can directly add the AngularJs Library in your theme or You can add directly in your portlet as well.

Now start write your code in portlet main.js file.

In this article you can see how Angular makes browsers intelligent— without the use of any other third party plugins.

What you Learn in this article:-

  • Examples of how to use client-side data binding to build dynamic views of data that change immediately in response to user actions.
  • See how Angular sync your data in view without the need for DOM manipulation.
  • Learn a better, easier way to create AngularJS based portlet that works independently with your application

Getting Started

AngularJS is using HTML Declarative Approach to write and extend HTML code with custom attributes and elements. It’s also helps you to in Data Binding. You have to create one pure static HTML page then examine how we can convert this HTML code into a template that angular will use to display dynamic data.

So here is Static HTML code:-

In AngularJS, the view is a magnification of the model through the HTML template so whenever we change anything in the model angular refreshes the same binding points and updates in the view.

The view component is frame by Angular from this template:

docroot/view.jsp:

We replaced the HTML news list with the ngRepeat directive and Angular expressions:

  • The ng-repeat=”news in newslist” attribute in the
  • tag is an Angular repeater directive. The repeater tells Angular to create a
  • element for each news in the list using the
  • tag as the template.
  • The expressions wrapped in curly braces {{ }} will be replaced by the value of the expressions.

We have added a new directive, called ng-controller, which attaches a NewsListCtrl controller to the parent tag.

  • The expressions in curly braces {{ }} show bindings, which are referring to our NewsListApp model, which is set up in our NewsListCtrl controller.

Now Build your portlet. After completing successful build go to your browser open your localhost site and just drag the portlet in layout to see the result.

Note: We have specified to load Angular Module using ng-app=”NewsListApp”, where NewsListApp is the name of our module. This module will contain the NewsListCtrl.

How to configure AngularJS Plugin in Liferay

 

AngularJS IDE plugin is based on tern.java to manage powerful completion on HTML files (AngularsJS Expression, directive, modules) and Javascripts files.

Configure AngularJS Plugin in Liferay

AngularJS IDE Plugin help you to extend Liferay web development tool and enhance the capabilities of UI development in liferay:

  • HTML editor which supports AngularJS expression and directive.
  • Angular Explorer view which displays modules, controllers of your project in a tree structure.
  • Javascript editor which supports AngularJS features (modules, etc).

Follow this below steps to configure the angularjs plugin in liferay

  • Go to : Help > Click on Install New Software
  • Copy and paste this URL in Work with textbox “Anularjs – http://oss.opensagres.fr/angularjs-eclipse/0.7.0/”
  • Anularjs – http://oss.opensagres.fr/angularjs-eclipse/0.7.0/

We need to select only those components who are not installed on you Liferay Developer Studio.

Click on checkbox “Hide items that already installed”

Install Angular

Click on Next Button.

After installation of all the components you can convert your Project.

  • Right click on your project > Configure > Convert to AngularJS Project

AngularJS Eclipse is based on the javascript inference engine tern.js is written in JavaScript. To use it You must configure node.js. You can also do it this with Rhino but it’s too slow for that .To do that you can :

  • Now Go to Window > Prefrences > Select Tern:

when the native node is selected, in default folders installation, it explores node binary (ex : “C:\Program Files\nodejs\node.exe” for Windows) and if it doesn’t locate, it seeks in your node in your “PATH” environment. For that you have to set PATH enviroment in your system.

You can download node.js from this link. you must install the node.js according your OS Configuration :

Install nodeJS

Right Click on your Project properties and verify the angular plugin

Angular-module

Angular plugin will offer you to recover controllers,module, (custom) directives while writing a code. Here you can also see the list of other modules are available which we can select and enable as per the project requirement.

Set your Script path:

scrpt-path

Settings of AngularJS Directives Syntax

Angular is using several syntax of declaring directives like starting with ‘x-‘, ‘data-‘ and use ‘:’, ‘-‘, ‘_’ delimiters.

directives

Here ,we have finished to configure AngularJS IDE Plugin, now it’s time to write the code and start your first web application with Liferay.