AngularJS Component Frameworks: Introducing PrimeNG

By Cristian Ionescu

WEBINAR: On-demand webcast

How to Boost Database Development Productivity on Linux, Docker, and Kubernetes with Microsoft SQL Server 2017 REGISTER >

PrimeFaces is a set of 100-inch JSF-compliant UI components. These PrimeFaces components support Ajax compatibility and are compatible with most browsers used by the vast majority of Internet users.

And, let's not forget the WIP project called PrimeNG, which is a collection of rich UI components for AngularJS2. All these collections have been developed by the PrimeFaces team (Cagatay Civic leader) and are defined as "Ultimate UI Framework for Java EE." PrimeNG is open source under the Apache license and hosted at GitHub.

PrimeNG delivers a set of predefined components ready to use, namely: menus, tree tables and data tables, Drag & Drop function, dialogs, charts. To see all PrimeNG components, visit http://www.primefaces.org/primeng.

Before writing an AngularJS 2 application, we need first to set our development environment, by installing the needed frameworks, as you will see in the first section of this article. The library itself can be installed using npm from a command line or by adding the following line in the .json package.

Installation

First, we need to install Node.js (node and npm). You should install the Node.js distribution compatible with your operating system. Next step is to create the project folder, choose a location on your computer and create a new folder named, angular2 ; this folder will contain all the files of our application. In the angular2 folder, we need to add three JSON files: one to guide the TypeScript compiler, one that identifies missing TypeScript definition files and one that defines the packages and scripts we need. These three JSON files and their descriptions are listed below:

Guide TypeScript Compiler

The first one is named tsconfig.json and its standard content should look like this:

{
 "compilerOptions": {
 "target": "ES5",			//  Specify ECMAScript target version
 "module": "system",		// Specify module code generation
 "moduleResolution": "node",	// Specifies module resolution strategy
 "sourceMap": true,			// Generates corresponding '.map' file
 "emitDecoratorMetadata": true,	// Emit design-type metadata for decorated declarations in source
 "experimentalDecorators": true,	// Enables experimental support for ES7 decorators
 "removeComments": false,		// Do not emit comments to output
 "noImplicitAny": false,		// Warn on expressions and declarations with an implied 'any' type
 "declaration": true		// Generates corresponding d.ts files
},
 "exclude": [				// Points folders and file to exclude	
 "node_modules",
 "typings/main",
 "typings/main.d.ts"
 ]
}

The content of this file and its values may differ; but, in order to modify its content/values, you have to understand first the meaning of each entry. A good start for learning TypeScript can be found in the official tutorial.

Identify the Missing TypeScript Definition Files

The second JSON file is also based on TypeScript. Is named typings.json and it should be located in angular2 folder. Its content identifies missing TypeScript definition files:

{
 "ambientDependencies": {
  "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim/es6-
                      shim.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd",
  "jasmine": 
   "github:DefinitelyTyped/DefinitelyTyped/jasmine/
                      jasmine.d.ts#7de6c3dd94feaeb21f20054b9f30d5dabc5efabd"
  }
}

Define the Packages and Scripts We Need

At last, we add the package.json file in angular2 folder. This file is used by npm to install the pointed artifacts. Practically, Angular2 relies on the npm package manager to install the libraries needed by the application. The starter-set of packages should by specified in the dependencies and devDependencies sections:

{
 "name": "angular2",  // Name of the application's folder
 "version": "1.0.0",
 "scripts": {
    "start": "concurrently \"npm run tsc:w\" \"npm run lite\" ",    
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "lite": "lite-server",
    "typings": "typings",
    "postinstall": "typings install" 
},
 "license": "ISC",
 "dependencies": {
    "angular2": "2.0.0-beta.12",
    "systemjs": "0.19.24",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.6.6"
},
 "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.1.0",
    "typescript": "^1.8.9",
    "typings":"^0.7.9"
 }
}

The complete documentation for package.json can be found here.

The npm Commands

Now, we can run the npm commands. From the command line, navigate in angular2 folder and type the command below:

npm install

 

Note: In case you see some errors (in red) do not worry. The install typically recovers from these errors and finishes successfully.

As you can see in the above figure, the result of running npm install command is one folder: node_modules and a new text document: npm_debug.

The structure of the newly created folder node_modules should look like this:

Create the Application Folder

After a successful installation, the next step is to create the application folder that is named app and we manually create it and locate it in our project folder, angular2. At this point we have finished all the prerequisites and we can start developing the application.

Create the Component File

In order to start developing the application, we need first to create the component file. Practically, we build an AngularJS 2 application by creating and shaping components. These components behave as the foundation of our application. It is mandatory to define at least one component, and for this we should write a *.ts file. Our example will be simple "Hello HTMLGoodies!" example, so we can name our file as app.helloHTMLGoodies.ts, and place it in the /angular2/app sub-folder.

The app.helloHTMLGoodies.ts content will be:

import {Component} from 'angular2/core'; 
 
 @Component({ 
 selector: 'HTMLGoodies', 
 template: '<font color="#002D7C"><h3>Hello HTMLGoodies!</h3></font>' 
 }) 
 
 export class AppComponent { 
 }

1: AngularJS 2 is built in a modular way, that means that we can build our components by importing the right artifacts from the right modules in our component. Typically, you will import at least the Component artifact (decorator function) from the angular2/core module. This is needed for defining a component.

3: The Component is a decorator function that takes a metadata object; by using metadata we model the look and comportment of our component. A function can be applied to a component by prefixing it with @.

4-5: These two lines represents the fields of our metadata object. Typically, these two fields will be contained by each component, but there are more optional fields, such as directives, providers or styles.

4: The selector field is part of the metadata object. Normally, this field points to a CSS selector for an HTML element that represents the component. In our case, the element for this component is named hello-world. This element will be used in our HTML application, and AngularJS will instantiate our component for each occurrence of hello-world.

5: The template field is also part of the metadata object. Via this field, we indicate the HTML markup that should be rendered for the hello-world occurrence. We will simply render the text Hello world!. The template can be very complex; it may contain data bindings, use other components, etc.

8-9: The AppComponent is the component class. Here is the business logic of our component. For example, here we can fire HTTP requests, invoke services, have routings, etc. In our case, the component class is empty, since we simply want to display plain text. But, as you can see, even if it is a do-nothing class, we cannot skip its signature! The export meaning is fairly clear. We need to export our component so that we can import it elsewhere in our application.

Pointing to the Root Component

The root component acts as a "starting" point for our component tree.

In an Angular 2 application, we need to tell Angular when to start up. This is done using the bootstrap method, passing in our AppComponent along with other module dependencies. Once the application is bootstrapped, Angular looks for our root component in our markup.

The root component should be defined in a new file named main.ts in /app folder, as below:

import {bootstrap} from 'angular2/platform/browser'; 
import {AppComponent} from './app. helloHTMLGoodies;
bootstrap(AppComponent); 
  1. We import the bootstrap decorator function specific for applications that run in a web browser. Most probably, your first AngularJS 2 applications will use the Angular's browser bootstrap function, since the web browser is the easiest way to test your work. But, you have to know that Angular2 can load a component in a different environment (e.g. on mobile devices). In such cases, the bootstrap function must be loaded from specific libraries, not from angular2/platform/browser.
  2. We import our AppComponent function.
  3. We bootstrap/load our root component.

Note: You can merge these two .ts files in a single one, but this is the recommended and proper way to structure an Angular2 application.

Create the Web Page of our Application

Now it is time to show our component in a web page.

We will name this page index.html and we will place it in the /angular2 folder. Its content is listed below:

<html> 
<head> 
<title>Angular 2 Hello HTMLGoodies</title> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<link rel="stylesheet" href="styles.css"> 

<!-- 1. Load libraries --> 
<!-- IE required polyfills, in this exact order --> 
<script src="node_modules/es6-shim/es6-shim.min.js"></script> 
<script src="node_modules/systemjs/dist/system-polyfills.js"></script> 
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script> 
<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script> 
<script src="node_modules/systemjs/dist/system.src.js"></script> 
<script src="node_modules/rxjs/bundles/Rx.js"></script> 
<script src="node_modules/angular2/bundles/angular2.dev.js"></script> 

<!-- 2. Configure SystemJS --> 
<script> 
System.config({ 
packages: { 
app: { 
format: 'register', 
defaultExtension: 'js' 
} 
} 
}); 
System.import('app/main') 
.then(null, console.error.bind(console)); 
</script> 
</head> 

<!-- 3. Display the application --> 
<body> 
<HTMLGoodies>Loading...</HTMLGoodies> 
</body> 
</html>

As you can see, there are three main sections:

Section 1: load libraries

In this section we need to add the JavaScript libraries needed to run our application. Depending on the application complexity, the number of these libraries may increase, but the minimum requirements involve:

IE requires polyfills to run an application that relies on ES2015 promises and dynamic module loading

<script src="node_modules/es6-shim/es6-shim.min.js"></script> 
<script src="node_modules/systemjs/dist/system-polyfills.js"></script> 
<script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script> 

polyfills for Angular2

<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script> 

SystemJS library for module loading

<script src="node_modules/systemjs/dist/system.src.js"></script> 

Reactive Extensions RxJS library

<script src="node_modules/rxjs/bundles/Rx.js"></script> 

Web development version of Angular 2 itself

<script src="node_modules/angular2/bundles/angular2.dev.js"></script>

Section 2: Configure SystemJS

In order to load application and library modules, AngularJS 2 supports different approaches. The recommended approach, though not mandatory, is based on SystemJS. If you are not open to learn more about SystemJS then you can follow this scaffold:

<script> 
	System.config({ 
		packages: { 
			app: { 
				format: 'register', 
				defaultExtension: 'js' 
			     } 
			    } 
 }); 

System.import('app/main').then(null, console.error.bind(console)); 

</script> 

Mainly, this code can be explained like this:

  • The packages node instructs SystemJS regarding the actions that should be accomplished in case of a request for a module from the app/ folder.
  • The packages: configuration tells SystemJS to default the extension to js, a JavaScript file.

The System.import call tells SystemJS to import the main file (main.js - after transpiling main.ts).

Section 3: Display the application

Displaying the application to the client involves the "replacement" of the hello-world tag with the proper template. Remember that this tag is actually a selector in our component. When the bootstrap() function is called, Angular2 process our component and locates the metadata object that contains the hello-world selector. Furthermore, it locates the hello-world tag and loads our application between those tags. The element tag and the selector must have the same name.

Run the Application

At this moment the development phase of our application is over. It is time to run it.

Running the application is very simple. Open a Node.js command prompt and go through the project folder (angular2) path and run the following command:

npm start

This command will compile our application via two parallel node processes:

  • The TypeScript compiler in watch mode
  • The result of compilation will produce in /app folder the following files:
  • app.helloworld.d , app.helloworld.js, app.helloworld.js.map
  • main.d , main.js, main.js.map
  • A static server called lite-server will load the index.html in a browser
  • The browser will be refreshed when application files change
  • The application host will be localhost and the port will be 3000

A possible output will look like the figure below:

After the above output, in a few seconds, your default browser will be automatically started and you should see the below output:

After a few seconds the message from the right side of the browser window will disappear.

Summary

This article has taught you how to make a simple Hello HTMLGoodies example using AngularJS 2 and PrimeNG UI components.



Make a Comment

Loading Comments...

  • Web Development Newsletter Signup

    Invalid email
    You have successfuly registered to our newsletter.
  •  
  •  
  •  
Thanks for your registration, follow us on our social networks to keep up-to-date