#native_company# #native_desc#
#native_cta#

Using AngularJS 2 in PHP via PrimeNG UI Components

By Octavia Andreea Anghel
on June 17, 2016

In this article, you will see how to use AngularJS 2 in PHP via the PrimeNG UI components. First we need to create an AngularJS 2 application from the beginning and then we will create a project. Finally, we will run the project.

Before writing an AngularJS 2 application, we need to first to set our development environment by installing the needed frameworks.

Installation

First, we need to install Node.js (node and npm). You should install the Node.js distribution compatible with your operating system.

The 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. All three of these JSON files and their description 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 first understand 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. It is named typings.json and it should be located in the 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 Needed

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 command line navigate in angular2 folder and type the command below:

npm install

Note: In the event that 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 figure above, the result of running npm install command is the two new created folders: node_modules and typings.

Create the Application Folder

The application folder is named app and we manually create it and locate it in our project folder, angular2. So, 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 Angular2 JS application by creating and shaping components. These components behave as the “bricks” of our application. It is compulsory to define at least one component, and for this we should write a *.ts file. Our example will be an “Hello World!” example, so we can name our file as app.helloworld.ts, and place it in the /angular2/app sub-folder.

The app.helloworld.ts content will be:

1: import {Component} from 'angular2/core'; 
2: 
3: @Component({ 
4: selector: 'hello-world', 
5: template: '<h1>Hello World!</h1>' 
6: }) 
7: 
8: export class AppComponent { 
9: }

1: Angular2 JS 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 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 using the @ prefix.

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 metadata object; practically, 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 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 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 pretty 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:

1: import {bootstrap} from 'angular2/platform/browser'; 
2: import {AppComponent} from './app.helloworld'; 
3: bootstrap(AppComponent);

1: We import the bootstrap decorator function specific for applications that run in a Web browser. Most probably, your first Angular2 JS 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 /angular2 folder. Its content is listed below:

<html> 
<head> 
<title>Angular 2 Hello World</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> 
<hello-world>Loading...</hello-world> 
</body> 
</html>

As you can see, there are three main section:

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 Angular2 JS supports different approaches. The recommended approach, but 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 about 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 client involve the “replacement” of 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 processes 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.

Services

Our application defines a Hello World example that is used to make an HTTP call to retrieve data. So let’s take a look at the service (service.ts file) and walk through the pieces:

import {Injectable}     from 'angular2/core';
import {Http}           from 'angular2/http';
import {Observable}     from 'rxjs/Observable';
import 'rxjs/Rx';

@Injectable()
export class HelloService {
  constructor (private http: Http) {}

  private _helloUrl = 'hello.php'; 

  goSayHello (name: string) : Observable<string>  {  
      
    var _paramUrl = this._helloUrl + "?name=" + name;  

    return this.http.get(_paramUrl)
                    .map(res =>  <string> res.text())
                    .do(data => console.log(data)) 
                    .catch(this.handleError)                  
  }
  
  private handleError (error: Response) {
    // in a real world app, we may send the error to some remote logging infrastructure
    // instead of just logging it to the console
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }
}

@Injectable() Decorator

In Angular 2 we use the Injectable decorator to let Angular know a class should be registered with dependency injection.

HTTP Service

The Angular 2’s HTTP library lets you call all your basic HTTP methods.

import ‘rxjs/Rx’ pulls in the RxJs library so we get access to methods on Observables. Without adding this line we wouldn’t be able to run .map() on the return from http.get() method since the returned Observable wouldn’t have the map method available.

PHP Script

Our hello.php script retrieves the name from the URL passed through the goSayHello() method and outputs it in the browser:

<?php

//outputs the converted special characters ,$_GET["name"], to HTML entities
echo 'Hello ' . htmlspecialchars($_GET["name"]) . '!';
?>

Run the Application

At this moment, the development of our application is over. It is time to run it. Running the application is very simple. From the project folder (angular2) 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 below:

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

Summary

This article has explained how to make a simple HelloWorld example using AngularJS 2 with PrimeNG UI components and PHP.