Posts on this Category



Adding the Multiselect feature to an Angular2 Autocomplete

Angular2 Multi Selection Autocomplete
Angular2 Multi Selection Autocomplete

After I wrote the tutorial on how to create an angular2 autocomplete, lots of people have been asking me to add the multiselect feature to it, that’s the reason why I decided to write this one. I’m going to continue from where I stopped, so make sure you followed and understood every step from the previous tutorial before you proceed.

The first thing we have to do is to create a variable called selected, it’s just an array we’re going to use to store all the items selected by the user.

public selected = [];

Now let’s change a little bit the select() function, instead of assigning the item to the this.query variable we’re going to add it to the selected array and clean the this.query. This is the modification that will make the multiple selection possible. Here’s the code after the modification:

select(item){
    this.selected.push(item);
    this.query = '';
    this.filteredList = [];
}

We also need a way to remove items from the array, I’m going to create a function called remove (obviously), here’s the code:

remove(item){
    this.selected.splice(this.selected.indexOf(item),1);
}

This is a really straightforward function, it just receives an item and uses the splice() function to remove it from the array.

The template will also suffer some changes:

<div class="container" >
    <div class="input-field col s12">
      <input id="country" type="text" class="validate filter-input" [(ngModel)]=query (keyup)=filter()>
      <label for="country">Country</label>
    </div>
    <div class="suggestions" *ngIf="filteredList.length > 0">
        <ul *ngFor="#item of filteredList" >
            <li >
                <a (click)="select(item)">{{item}}</a>
            </li>
        </ul>
    </div>
    <div *ngFor="#item of selected">
        <div class="selected" >
            <span>{{item}}</span>
            <a (click)="remove(item)">x</a>
        </div>
    </div>
</div>

Notice that I’ve added another div bellow the suggestions list, that’s where the selected items will be displayed, also notice that each item will an ‘x’ that will call the remove function when clicked.

Lastly we have to do the styling, in this example I’ve used the following css to adjust how the selected items are displayed, but feel free to do as you like.

.selected{
	border:solid #4CAF50 1px;
	float:left; 
	margin:2px;
	padding:2px 15px;
}
 
.selected a{
	cursor:pointer;
	font-weight:bold;
}

That’s it guys! With just a few changes we can now select multiple items with our autocomplete, just leave a comment if you have any doubts.

Angular2 Tutorial: Creating Awesome Animated Charts with Highcharts

Highcharts with Angular2
Highcharts with Angular2

Today I’m going to show you how you can add some really amazing animated charts to your Angular 2 application. We’re going to use a very rich library called Highcharts, it provides a huge variety of charts that you can use on your app. Seriously, they probably have any type of chart you can think about! The only drawback of using highcharts is that it’s not written in Angular 2, so there will be some limitations which I’ll explain later. Since we’re not going to rewrite the charts, this post will be more about how to integrate highchars into your Angular 2 project.

Before we start you obviously need a blank project, if you’re new to angular please follow the instructions on this quickistart to create your project. Having done that you have to add jQuery to the project in order to make highcharts work properly, click here for more details about jQuery and Angular 2 integration.

Now that you have the project let’s add the following scripts to the index.html:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>

If you followed the instructions from the quickstart your project should have a component called app.component.js, just open it and replace the existing code with the following one:

import {Component} from 'angular2/core';
 
declare var jQuery:any;
 
@Component({
    selector: 'my-chart',
    template: `<div style="width:60%" id="container"></div>`
})
export class AppComponent { 
	private data = [
			{
	            name: 'USA',
	            data: [null, null, null, null, null, 6, 11, 32, 110, 235, 369, 640,
	                1005, 1436, 2063, 3057, 4618, 6444, 9822, 15468, 20434, 24126,
	                27387, 29459, 31056, 31982, 32040, 31233, 29224, 27342, 26662,
	                26956, 27912, 28999, 28965, 27826, 25579, 25722, 24826, 24605,
	                24304, 23464, 23708, 24099, 24357, 24237, 24401, 24344, 23586,
	                22380, 21004, 17287, 14747, 13076, 12555, 12144, 11009, 10950,
	                10871, 10824, 10577, 10527, 10475, 10421, 10358, 10295, 10104]
	        }, 
            {
            	name: 'USSR/Russia',
	            data: [null, null, null, null, null, null, null, null, null, null,
	                5, 25, 50, 120, 150, 200, 426, 660, 869, 1060, 1605, 2471, 3322,
	                4238, 5221, 6129, 7089, 8339, 9399, 10538, 11643, 13092, 14478,
	                15915, 17385, 19055, 21205, 23044, 25393, 27935, 30062, 32049,
	                33952, 35804, 37431, 39197, 45000, 43000, 41000, 39000, 37000,
	                35000, 33000, 31000, 29000, 27000, 25000, 24000, 23000, 22000,
	                21000, 20000, 19000, 18000, 18000, 17000, 16000]
	        }];
 
    ngAfterViewInit() {
    	this.renderChart();
    }
 
    renderChart(){
    	jQuery('#container').highcharts({
	        chart: {
	            type: 'area'
	        },
	        title: {
	            text: 'US and USSR nuclear stockpiles'
	        },
	        subtitle: {
	            text: 'Source: thebulletin.metapress.com'
	        },
	        xAxis: {
	            allowDecimals: false,
	            labels: {
	                formatter: function () {
	                    return this.value;
	                }
	            }
	        },
	        yAxis: {
	            title: {
	                text: 'Nuclear weapon states'
	            },
	            labels: {
	                formatter: function () {
	                    return this.value / 1000 + 'k';
	                }
	            }
	        },
	        tooltip: {
	            pointFormat: '{series.name} produced <b>{point.y:,.0f}</b>' +
	            			 '<br/>warheads in {point.x}'
	        },
	        plotOptions: {
	            area: {
	                pointStart: 1940,
	                marker: {
	                    enabled: false,
	                    symbol: 'circle',
	                    radius: 2,
	                    states: {
	                        hover: {
	                            enabled: true
	                        }
	                    }
	                }
	            }
	        },
	        series: this.data
	    });
    }
}

Now let me explain what is happening on this code, the most important thing is the method renderChart() called by the hook ngAfterViewInit(), as the name suggests it contains the code responsible for rendering the component, it’s where I’m providing all the parameters like title, labels, size and colors so highcharts can create the chart for me (you can check all the available options at the Highcharts API Reference). Lastly, jQuery will replace the only div in the template with the chart returned by highcharts.

Note that once renderChart() is called Angular 2 has no control over the component anymore, highcharts and jQuery are doing the entire job, which means Angular 2 won’t know how to deal with the chart once it’s created, and it won’t be able to automatically refresh it if something changes, as far as angular knows there’s just a div on the screen, so every time the data is modified you’ll have to call renderChart() again to be able to refresh the chart, that’s the limitation I was talking about.

That being said, you can now run your project and start customizing your chart! Please leave a comment if you need any help.

Using jQuery with Angular2

I know the idea of using jQuery with Angular2 may seen a little bit weird for lots of you, as we all know, Angular2 is responsible for managing everything related to our view components and DOM elements, it doesn’t sound like a good idea to use another framework to do a job Angular can easily do.

That being said, why would someone want to integrate jQuery with Angular2?

Well, there are some cases we still have to use jQuery, like for example, reusing some jQuery code or components when it’s not feasible to rewrite everything in Angular2, that’s probably the reason why you’re reading this tutorial.

Now let’s see how we can do this, it’s actually really simple, basically all you have to do is to add the jQuery script to your index.html and declare jQuery on your component, here is an example:

import {Component} from 'angular2/core';
 
declare var jQuery:any;
 
@Component({
    selector: 'my-app',
    template: `<button onclick="console.log('It Worked!!')">
                    jQuery Integration Test
               </button>
              `
})
 
export class AppComponent { 
 
    ngAfterViewInit() {
        jQuery('button').click();
    }
}

When you run your application you’ll see the text ‘It Worked!!’ on your console. That’s it!! This was a very short tutorial, but I hope it was helpful for you, just leave a comment if you have any doubts.

Angular2 Tutorial: Developing a Realtime Chat App

Angular 2 Chat Application
Angular 2 Chat Application

Hi guys, today we’re going to make an awesome chat application with Angular2, NodeJS and Socket.io, this tutorial will involve quite a lot of things, and there are also lots of small details, so it will be a little bit longer than usual. To easily understand and make the most of it you should already have some knowledge about all the frameworks involved, if something is unclear for you please let me know in the comments, I’ll try to explain it better. With that in mind let’s stop wasting time and get started!

Setting up the Environment

I’m going to use Express to create my project, if you’re new to express and don’t know how to do it click here to see the instructions. After creating the project there will be a file called package.json on the project folder, that’s where all the dependencies are listed, open this file and copy/paste the following code:

{
  "name": "angular2-chat",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "postinstall": "npm run typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "start": "concurrent \"node ./bin/www\" \"npm run tsc:w\"",
    "typings" : "typings"
  },
   "license": "ISC",
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "morgan": "~1.6.1",
    "serve-favicon": "~2.3.0",
    "angular2": "2.0.0-beta.16",
    "systemjs": "0.19.26",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.6.12",
    "socket.io":"1.4.5"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings":"^0.8.1"
  }
}

Besides the NodeJS and Express dependencies (which were already there), I’ve also added Socket.io and everything related to Angular2. If you run the command npm install on your terminal it’ll download and put all the dependencies on a folder called /node_modules. Lots of scripts from this folder will be used on the front-end, so we have to reference them on the index.html file, which we’re going to create right now.

Open the /views folder and create the index.html with the following code:

<html>
  <head>
    <base href="/">
    <title>Chat</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">   
    <script 
      src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.min.js"></script> 
    <script src="scripts/es6-shim/es6-shim.min.js"></script>
    <script src="scripts/systemjs/dist/system-polyfills.js"></script>
    <script src="scripts/angular2/bundles/angular2-polyfills.js"></script>
    <script src="scripts/systemjs/dist/system.src.js"></script>
    <script src="scripts/rxjs/bundles/Rx.js"></script>
    <script src="scripts/angular2/bundles/angular2.dev.js"></script>
    <script src="scripts/angular2/bundles/router.dev.js"></script>
    <script src="javascripts/jquery.js"></script>
    <link rel="stylesheet" 
      href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">
    <script 
      src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"></script>
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('javascripts/app/main.js')
            .then(null, console.error.bind(console));
    </script>
  </head>
  <body>
    <chat-app>Loading...</chat-app>
  </body>
</html>

This file is very similar to the one from Angular2 Quickstart, but as you can see I’ve added three more scripts: Socket.io and the Materialize css and js files (materialize is a CSS framework we’re going to use for styling). If you pay attention to this code you should notice that I’m not referencing the scripts from /node_modules, instead they’re coming from a folder called /scripts. But where does this folder come from? I’m going to explain in a moment.

One more thing, in order to make Angular2 work you’ll need three more configuration files : tsconfig.json, typings.json and main.ts. All of them can be found on the Angular2 Quickstart.

Now let’s open the app.js file that Exapress created for us, you’ll see that it already has some code, in order to make things easier I’m going to get rid of some lines of code we don’t need, after the modifications the file should look like this:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
 
app.use('/scripts', express.static(__dirname + '/node_modules/'));
app.use('/templates', express.static(__dirname + '/views/templates/'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
 
app.use('/', routes);
 
/* Handle 404. */
app.use(function(req, res, next) {
  res.sendFile(path.join(__dirname, 'views', 'index.html'));
});
 
module.exports = app;

Just after the var app = express(); line I’ve configured the paths /scripts (which we saw in the index.html) and /templates to serve some static files from /node_modules and /views/templates respectively. I had to do this because by default Angular 2 won’t have access to these folders. But now, if I request a file from /scripts this configuration will make NodeJS understand that it’s located on /node_modules.

At the end of the code (just above module.exports) I’ve changed how 404 errors are handled, instead of forwarding an error (as it was before) I’m redirecting to index.html. This will avoid some problems when we start using Angular2 routes.

Another thing we have to do is to make NodeJS and Angular2 work together, open the file /routes/index.js and replace the existing code with the following:

var express = require('express');
var router = express.Router();
var path = require('path');
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
 
module.exports = router;

By default it was rendering a .jade file (express uses jade as the default view engine), and as I’m not interested in jade for this project I just changed this file a little bit in order to make it redirect to my index.html where Angular2 can control the views. For more details about this modification click here.

At this point we’ve already configured everything we need in our project to start developing our chat app, new let’s start talking about how the application is going to work.

Defining the Structure

Our chat app will be composed of three Angular2 components, the first one will be a form where the user will be allowed to enter his name and join the chat, the second will be the chat itself, and the last will be where we’re going to configure to routes for controlling which of the other two components should be displayed.

On the back-end we’ll have Socket.io being responsible for receiving the messages and delivering them to all the other users, we won’t store the messages there, each client will have its own messages list where every received message will be added.

Creating the Socket.io Server

Before we proceed to the front-end we first have to create the Socket.io server and prepare it to receive messages from the clients, to do that you have to create a new file on your project root folder called socket.js with the following code:

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
 
var chat = {
	start: function(){
		server.listen(8000);
		io.set("origins", "*:*");
 
		io.on('connection', function (socket) {         // line 12
			socket.on('newMessage', function (data) {
				socket.emit('chatUpdate',data);
				socket.broadcast.emit('chatUpdate',data);
			});
			socket.on('newUser', function (data) {
				socket.emit('chatUpdate',
					{'userName':'','text':data+' has entered the room'});
				socket.broadcast.emit('chatUpdate',
					{'userName':'','text':data+' has entered the room'});
			});
		});	
	}
}
 
module.exports = chat;

Now probably is the best time for me to explain how Socket.io works, according to the official site Socket.IO is a framework that enables real-time bidirectional event-based communication, in other words you can create your own events that will allow the server to communicate with the clients and vice-versa. You can add listeners to these events and also emit events from both sides (client and server), once an event is emitted it will trigger its listener on the other side to execute an specific task. To emit events you can use the function emit() passing the event name and your data, and to add a listener you have to use the function on() with the event name as the first parameter and the callback function as the second.

Easy, right? Now that you understand how Socket.io works let’s analyze our code. The first thing I did here was to create a socket.io server that listens on port 8000, but let’s focus on the events, on the server side there is one event that we always have to use in order to start the communication with the clients, this event is called connection, it will be automatically emitted by the each client when it connects to the server (obviously), clearly we have to add a listener to proceed with the communication, as you can see in the code I’m doing it on line 12. Now take a look at the callback function associated with this listener, you’ll see that it’s registering listeners for two more events: newMessage and newUser. The first one is emitted when a user sends a message, and the second one when a new user joins the chat, the action performed by both is very similar, they will just emit another event called chatUpdate to notify all the connected clients about the new message or user. Note that when I emit this event I’m using both socket.emit() and socket.broadcast.emit(), the first one will notify the client who triggered the event, and the second will do the same to all the other clients.

Let’s add the following two lines bellow the var app = express(); on our app.js:

var socketServer = require('./socket');
socketServer.start();

Perfect! This will make the socket.io server initialize right after the application starts. We’re done with the back-end now, let’s start creating the angular2 components.

Creating the User Registration Component

We can finally start writing some Angular2 code, open the /public/javascripts folder and create a new one called /app, that’s where we’re going to put our angular2 components. Open this new folder and add a new file called userRegistration.component.js, then copy/paste the following code:

import {Component} from 'angular2/core';
import {Router} from 'angular2/router';
 
@Component({
    selector: 'user-registration',
    templateUrl: 'templates/registration.html'
})
export class UserRegistrationComponent {
    userName = '';
    socket = null;
 
    constructor(
        private _router: Router){}
 
    ngOnInit() {
        this.socket = io('http://localhost:8000');
    }
 
    login() {
        if (this.userName !== null){
            sessionStorage.setItem("userName", this.userName);
            this._router.navigate(['Chat']);
            this.socket.emit('newUser', this.userName);
        }
    }
 
    keypressHandler(event) {
        if (event.keyCode  === 13){
            this.login();
        }
    } 
}

This will be the component where the user is going to enter his name and join the chat, I’ve used the hook ngOnInit to connect to the Websocket server, this will automatically emit the connection event I just talked about. I also have the login() method, which is responsible for putting the provided userName on the sessionStorage and emit the newUser event. Although I’m using the sessionStorage to store the user, I don’t recommend you to do it, it’s not very safe, any user with some javascript knowledge will be able to modify what’s in the sessionStorge.

Note that I’ve created a new file to put the template, it’s called registration.html and it’s located on the folder /views/templates, here’s the code:

<style type="text/css">
	.registrationContainer{margin-top:20%;padding:15px;box-shadow: 3px 2px 7px -1px}
	.registrationContainer button{float: right;}
</style>
<div class="container">
	<div class="col s11 registrationContainer">
 
        <div class="row">
            <div class="input-field col s12">
                <input [(ngModel)]="userName" id="userName" 
                	type="text" (keypress)="keypressHandler($event)">
                <label for="userName">Please enter your name</label>
            </div>
        </div>
	    <button (click)="login()" type="submit" 
	    	class="btn waves-effect waves-light col s3"  
	    	name="action" >Login</button>
	    <div style="clear:both;"></div>
	</div>
</div>

Nothing special here, just an input where the user can type his name and a button to call the login() function. The CSS classes you can see here are from materialize.

Creating the Chat Component

Now comes the most important part, the chat.component.ts:

import {Component} from 'angular2/core';
import {Router} from 'angular2/router';
 
@Component({
    selector: 'chat',
    templateUrl: 'templates/chat.html'
})
export class ChatComponent {
    message = '';
    conversation = [];
    socket = null;
 
    constructor(
        private _router: Router){}
 
    ngOnInit() {
        if (sessionStorage.getItem("userName") === null){
            this._router.navigate(['Registration']);
        }
        this.socket = io('http://localhost:8000');
        this.socket.on('chatUpdate', function(data) {
            this.conversation.push(data);
        }.bind(this));
    }
 
    send() {
        this.socket.emit('newMessage', {
            'userName': sessionStorage.getItem("userName"),
            'text': this.message
        });
        this.message = '';
    }
 
    keypressHandler(event) {
        if (event.keyCode === 13){
            this.send();
        }
    } 
 
    isNewUserAlert(data){
        return data.userName === '';
    }
}

Again I’m using the ngOnInit hook to connect to server, but this time there are a couple more things I’m doing here, I’m checking the sessionStorage to see if it contains the userName, if it doesn’t the user will be redirected to the registration component, and I’m also adding a listener to the chatUpdate event, so when a new message arrives it’ll be added to the conversation array.

The send() method is responsible for triggering the newMessage event, it just get the message typed by the user and send it to the server, it’ll be executed when the user click on the send button or press enter.

Here’s the template:

<style type="text/css">
	.userLabel{font-weight:bold;color:#26A69A;margin-right:10px}
	.chatContainer{height:85%;padding:15px;overflow-y:auto }
</style>
<div class="col s12">
	<div class="col s12 chatContainer">
        <ul *ngFor="#msg of conversation" style="margin:0">
            <li >
            	<div *ngIf="!isNewUserAlert(msg)">
	                <span  class="userLabel" >{{msg.userName}}:</span>
	                <span>{{msg.text}}</span>
                </div>
            	<div *ngIf="isNewUserAlert(msg)">
            		<span style="font-weight:bold">{{msg.text}}</span>
	            </div>
            </li>
        </ul>
	</div>
	<div class="row">
		<div class="col s9">
          <input id="country" type="text"  
          	[(ngModel)]="message" 
          	(keypress)="keypressHandler($event)">
        </div>
		<button (click)="send()"  type="submit" 
			class="btn waves-effect waves-light s2"  name="action" >Send</button>
	</div>
</div>

Lastly we have the component app.component.ts to control the routing, with RouteConfig I’m defining the two possible routes of our app, this allows the other components to redirect from one to another. Note that in the template I have only the router-outlet which will basically render the component related to the current route.

import {Component} from 'angular2/core';
import {UserRegistrationComponent} from 'javascripts/app/userRegistration.component.js';
import {ChatComponent} from 'javascripts/app/chat.component.js';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
 
@Component({
    selector: 'chat-app',
    directives: [ROUTER_DIRECTIVES],
    template: `
            <router-outlet></router-outlet>
        `
})
@RouteConfig([ 
    { path: '/chat', name: 'Chat', component: ChatComponent, useAsDefault:true },
    { path: '/registration', name: 'Registration', component: UserRegistrationComponent }
])
export class AppComponent {}

To make the routes work we have to make a little modification in our main.ts, just add the ROUTER_PROVIDERS as follows:

import {bootstrap}    from 'angular2/platform/browser'
import {AppComponent} from 'javascripts/app/app.component.js'
import {ROUTER_PROVIDERS} from 'angular2/router'
 
bootstrap(AppComponent, [ROUTER_PROVIDERS]);

That’s it guys, we’ve completed our chat app, to run it just execute npm start and access it on your browser by typing localhost:3000. If you have any doubts please let me know in the comments, till next time!

Creating a NodeJS project with Express

Express is one of the most popular npm packages out there, it’s basically a NodeJS web application framework that provides lots of functionalities and helps you to manage everything and organize your app into MVC on the back-end, and it’s very easy to get started with.

To use Express you first need to have NodeJS installed (obviously), if you don’t have it yet click here and download the appropriate version for your OS. With nodejs installed you can now create your your project and start using express, in this tutorial I’m just going to cover how to create the project, but in the future I’ll probably write more about it.

Express has a tool called express-generator that is used to create the project’s basic structure, to install it just use the command:

npm install express-generator -g

Now that we’ve installed it globally we’re ready to create the project, open your terminal and navigate to the folder where you want to put your project, then simply run the command:

express myFirstExpressApp

Done! Now you have a folder called myFirstExpressApp (or any other name you’ve chosen), if you go inside it you’ll see the project files and the following folder structure:

Express Basic Project Structure
Express Basic Project Structure

Automatically Mapping JPA Entities with Netbeans

Creating the JPA entities manually can be really time consuming, specially if you’re working with a huge database with hundreds of tables. Luckily, Netbeans IDE can automatically create the entities for us, if you want to see how just follow the instructions bellow:

1 – Right click on your package -> New -> Entity Classes from Database:

New Entity Classes From Database
New Entity Classes From Database

2 – A new window will show up, but before you proceed you have to create a data source:

New Data Source
New Data Source

3 – Name it as you like and click on New Database Connection:

New Database Connection
New Database Connection

3 – You’ll be asked to select the database driver and also to provide the connection info, after that just click next and finish:

Providing Connection Info
Providing Connection Info

4 – Now you can already see a list containing your database tables, select the ones you want and click next, another screen with some options will show up but you don’t need to change anything, just hit next again and finish:

Selecting the Tables
Selecting the Tables

5 – That’s it! As you can see you already have the entities:

New Entities
New Entities

Improve Performance by Increasing Glassfish Memory

When a Glassfish domain is created it already comes with a default set of JVM options (including memory related options), as you keep working on your project your application will increasingly grow and consume more memory, until it reaches the point where the default Glassfish memory configuration isn’t appropriate to run your app anymore. If you are facing this problem you can easily increase the memory by following the instructions bellow:

1 – Open the glassfish console on your browser and click on server-config:

Glassfish Console
Glassfish Console

2 – Then click on JVM Settings:

Glassfish server-config screen
Glassfish server-config screen

3 – On the JVM Options tab these are the two options you may want to change: XX:MaxPermSize and Xmx.

Glassfish JVM Options
Glassfish JVM Options

As long as you have memory available on your server you can put any size you want here. After the modifications you just need to restart your server and you’re done!

Tutorial: Creating an Angular2 Autocomplete

Angular 2 Autocomplete
Angular 2 Autocomplete

Before we begin I just want to say that I’m not going to use any third-party component for this tutorial, I’m going to create an autocomplete from scratch, my goal is to just make it show the suggestions and allow the user to select one, but if you need more advanced features feel free to comment, I’ll do what I can to help you.

With that in mind, let’s start by creating our class, just copy/paste the code bellow:

export class AutocompleteComponent {
    public query = '';
    public countries = [ "Albania","Andorra","Armenia","Austria","Azerbaijan","Belarus",
                        "Belgium","Bosnia & Herzegovina","Bulgaria","Croatia","Cyprus",
                        "Czech Republic","Denmark","Estonia","Finland","France","Georgia",
                        "Germany","Greece","Hungary","Iceland","Ireland","Italy","Kosovo",
                        "Latvia","Liechtenstein","Lithuania","Luxembourg","Macedonia","Malta",
                        "Moldova","Monaco","Montenegro","Netherlands","Norway","Poland",
                        "Portugal","Romania","Russia","San Marino","Serbia","Slovakia","Slovenia",
                        "Spain","Sweden","Switzerland","Turkey","Ukraine","United Kingdom","Vatican City"];
    public filteredList = [];
    public elementRef;
 
    constructor(myElement: ElementRef) {
        this.elementRef = myElement;
    }
}

As you can see I’ve already added the data to my class, as I’m trying to make it simple it’s just an array of countries, but of course in a real case scenario the data would come from your database or via web service, also it wouldn’t be placed inside the component, it would be passed to it, this way the component could be reused with other data in other parts of the application.

I’ve also created the variables query and filteredList, the first one will hold the string typed by the user, and the second is where I’m going to store the suggestions being displayed by the component, its value will constantly change as the user types on the input. There is also the constructor where I’m setting the elementRef value, but I’ll get to that variable in a moment.

Now let’s create the methods to filter the data and select the item:

filter() {
    if (this.query !== ""){
        this.filteredList = this.countries.filter(function(el){
            return el.toLowerCase().indexOf(this.query.toLowerCase()) > -1;
        }.bind(this));
    }else{
        this.filteredList = [];
    }
}
 
select(item){
    this.query = item;
    this.filteredList = [];
}

These two functions are very straightforward, the filter() function uses the query variable to filter the countries, then it stores the result in the filteredList.

The select() is even simpler, I’m just assigning the selected item to the query variable in order to make it appear on the input, and to make the suggestions list disappear I’m removing everything from the filteredList.

Ok, we already have the two most important functions to make our component work, now we can create the template:

@Component({
    selector: 'autocomplete',
    template: `
        <div class="container" >
            <div class="input-field col s12">
              <input id="country" type="text" class="validate filter-input" [(ngModel)]=query (keyup)=filter()>
              <label for="country">Country</label>
            </div>
            <div class="suggestions" *ngIf="filteredList.length > 0">
                <ul *ngFor="#item of filteredList" >
                    <li >
                        <a (click)="select(item)">{{item}}</a>
                    </li>
                </ul>
            </div>
        </div>  	
        `
})

Note that I’ve used some different css classes here, some of them I created myself and some are from materialize, if you want to use them just add to your project the link to their css and js files.

At this point your autocomplete is already working, if you run your project you’ll see a result similar to the gif at the beginning of this tutorial, but there’s still a small problem we have to fix, note that once the suggestions list shows up you have to either erase the text from the input or select one to make the them disappear. The problem is that the user should be able to get rid of the suggestions by clicking anywhere other than the list, and to be able to do that we have to detect clicks outside the our component, more info here.

Remember the elementRef variable we saw in the constructor? Now we’re going to use it, the follwoing method tells whether the click occured in the component or outside it:

handleClick(event){
   var clickedComponent = event.target;
   var inside = false;
   do {
       if (clickedComponent === this.elementRef.nativeElement) {
           inside = true;
       }
      clickedComponent = clickedComponent.parentNode;
   } while (clickedComponent);
    if(!inside){
        this.filteredList = [];
    }
}

The function just gets the clicked component, navigates between its parent nodes and checks if one of them is the elementRef.nativeElement (which is our component), if it’s true the items from the filteredList are deleted in order to make the list disappear. Now we have to bind this method to the (document:click) event, this is how you can do it:

@Component({
    selector: 'autocomplete',
    host: {
        '(document:click)': 'handleClick($event)',
    },
    template: //TEMPLATE CODE HERE
})

That’s it!! As I said if you need more features or if you have any doubts just leave a comment, I’ll be glad to help!

Angular2 Tutorial: Detecting Clicks Outside the Component

Angular2 click detection
Angular2 click detection

Sometimes there is a need to detect whether the user is clicking inside or outside our angular2 component, specially if your component has a dropdown element, in this case you need to know exactly where the click occurred in order to perform the right action. In this tutorial I’m going to demonstrate with angular 2 a very easy way to determine if the click happened outside the component or not.

Let’s start by creating this very simple component:

import {Component, ElementRef} from 'angular2/core';
 
@Component({
    selector: 'click-detection-component',
    template: `
    	<div style="width:100px;height:60px;background-color:#f1f1f1"></div>
    	`
})
 
export class ClickDetectionComponent {
}

Nothing special here, it just renders a rectangle on the screen. Now my goal will be to show a different message when the click occurs inside and outside this rectangle, to do that we have to create a function to check if the clicked component belongs to my current angular2 component or not:

export class ClickDetectionComponent {
   public elementRef;
 
   constructor(myElement: ElementRef) {
       this.elementRef = myElement;
   }
 
   handleClick(event){
       var clickedComponent = event.target;
       var inside = false;
       do {
           if (clickedComponent === this.elementRef.nativeElement) {
               inside = true;
           }
           clickedComponent = clickedComponent.parentNode;
       } while (clickedComponent);
       if(inside){
           console.log('inside');
       }else{
           console.log('outside');
       }
   }
}

Here’s what is happening in this function: First I’m getting the clicked component from my event using event.target, then I’m navigating between its parent nodes checking is one of them is my elementRef.nativeElement, if it is, it means that the user clicked inside the component, otherwise it was outside.

Now comes the tricky part, if I bind this function to the div click event it will only be called when the user clicks on the div, therefore how am I going to be able to detect the clicks that occurs outside? To solve that I’m going to use the (document:click) event, this way the function will be called no matter where the user clicks.

You can add this event to your component like this:

@Component({
    selector: 'click-detection-component',
    host: {
        '(document:click)': 'handleClick($event)',
    },
    template: `
    	<div style="width:100px;height:60px;background-color:#f1f1f1"></div>
    	`
})

Perfect! Now if you run your project you can see the messages on the console telling whether the component was clicked or not.

Hope you enjoyed the tutorial, just leave a comment if you have any doubts.