An inbuilt support for dependency injection in AngularJS allows developers to write code which can manage dependencies across various objects. AngularJS provides Modules, Controllers, Directives, Filters, Services, Factories, etc. which can be used for developing logical layers on the client-side for Databinding, Ajax calls, sharing data across controllers, and so on. Since under the hood AngularJS uses the JavaScript language, it comes with some of the limitations of JavaScript e.g. Data Typing, Global Namespace and lack of typical Object Oriented programming features.
Why TypeScript for AngularJS applications?
TypeScript, a free and open source programming language from Microsoft can be used to overcome these shortcomings. TypeScript is a typed superset of JavaScript which compiles to plain JavaScript. This is a strongly typed language and provides class-based OOPs like experience for designing JavaScript applications.
TypeScript can improve refactoring and quality of angularjs applications. Another point to note in favor of using TypeScript for AngularJS apps is that the next version of Angular (Angular 2, currently in RC) uses TypeScript , so current AngularJS applications developed using TypeScript have a better chance of a smoother transition to Angular 2.
AngularJS with TypeScript - Technical Prerequisites
To implement the application in this following article, the following prerequisites must be satisfied
The Implementation
To implement our application, we will be using Visual Studio Code and Node.js.
After installing Node.js and Visual Studio Code, we will need TypeScript using the instructions in this link. On Windows OS and with Visual Studio 2013 or 2015 IDEs, we can download project templates for TypeScript from this link.
Step 1: Since we need to create a project workspace for our AngularJS application, create a new folder on your hard disk. Open VS Code. Using File > Open Folder, open the folder in the Visual Studio Code to create all files in the same folder workspace.
Step 2: To install TypeScript using Node Package Manager (npm), open the Node.js Command Prompt and navigate to the Folder created in the Step 1. Run the following command from the Command Prompt
npm install TypeScript -g
This will install TypeScript globally so that we can use its transpiler (compiler) to convert TypeScript to JavaScript.
Step 3: Using VSCode IDE, add a new folder in the project of name views, scripts and styles. As mentioned in Step 2, navigate to the scripts folder in the Command prompt and run following commands
npm install angular
npm install angular-route
This will install the AngularJS framework and routing library for the current project.
Navigate to the styles folder and run the following command
npm install bootstrap
In the project, add a new file with the name as index.html. This will be our view file to display UI. Since we need to define TypeScript project settings for the application, add a new file in the project of name tsconfig.json and add the following code in it
{
"compilerOptions": {
"target":"es5",
"module":"amd",
"sourceMap":true
}
}
Get more information about this file from this link.
We need to define a Task for the project so that it can invoke the TypeScript Transpiler to compile TypeScript into JavaScript. Press Ctrl+Shift+B in VSCode, this will show the Configure Task Runner option at the top of the IDE as shown in the following image
Click on the Configure Task Runner to add tasks.json file in the project. This will contain several lines of code with and without comments as shown in the following image. (The Image shows only uncommented code),
Replace the “args” value to blank. (Delete HelloWorld.ts).
After Step 3, the project structure will be as shown below:
Step 4: In the project, we need intellisense for AngularJS. In VS Code we can implement it using Type Definition files (.d.ts). To install the required intellisense files run the following commands from the command prompt. (Note: In previous step we have navigated to the scripts folder, using cd.. navigate back to its parent.)
tsd install angular --resolve --save
This will install the angular.d.ts file. The –resolve switch will resolve all dependencies needed for angular.d.ts, in this case the dependency is jQuery.d.ts. The project will add typings folder containing angular.d.ts and jQuery.d.ts. It will also contain tsd.d.ts containing references for angular and jquery. The file tsd.json will be added to the project which defines required configurations for these files.
Step 5: In the project, add a new file of the name logic.ts. We will add necessary logic in this file. In VS Code, AngularJS intellisense will be displayed as shown here:
Step 6: In the logic.ts file, we will add code for creating angular module and controller using TypeScript features line interfaces, classes, etc. The interface will define all methods and properties to be exposed to the view for databinding purpose. The angular Controller will be implemented using TypeScript class. This class will contain properties, methods, constructor, etc. The Constructor function of the controller class will be used to inject dependencies to the controller. Finally, we will register the TypeScript controller in our Angular module.
Adding Angular module
In the logic.ts, add the following line
var app = angular.module('app',[]);
This is an Angular module, and has the same syntax as the JavaScript declaration of the angular module. It’s the same because TypeScript is a superset of JavaScript.
Adding the interface
In the logic.ts add the following interface
interface IEmployee{
header:string,
Employees:any[];
}
In the TypeScript interface of name IEmployee, we have declared header property of type string and the Employees array of type any. The any type of TypeScript will allow us to store any type of data on Employees array varying from string to numeric or a JSON object.
Adding the Controller class using TypeScript Class
In logic.ts, add the following TypeScript code. This is the class which implements IEmployee interface and all its properties.
class EmployeeCtrl implements IEmployee{
header:string;
Employees : any[];
constructor() {
this.header = "Employee List";
this.Employees=[
{
"EmpNo":101,
"EmpName":"MS",
"Salary":20000
},
{
"EmpNo":102,
"EmpName":"LS",
"Salary":18000
},
{
"EmpNo":103,
"EmpName":"TS",
"Salary":16000
}
];
}
}
The class EmployeeCtrl implements IEmployee and implements all its properties. The Constructor function initializes the header and Employees array properties. Let’s compile the TypeScript code. We have already added the tasks.json which is the Task Runner, this file contains tsc command for calling transpiler for TypeScript to generate JavaScript code. Press Ctrl+Shift+B to generate JavaScript. The following image shows the JavaScript code generated.
As we know that we use function to create classes in JavaScript, on the same basis we have EmployeeCtrl function containing all the declaration of TypeScript class. The above code shows the EmployeeCtrl is in the global namespace in JavaScript, and this contains EmployeeCtrl function in it in IIFE (immediately invoked function expression). So here we need to be careful about the registration controller in the Angular module. To do so, we will add the registration at the bottom of the logic.ts file. Add the following line at the bottom of the logic.ts after the class code ends.
angular.module('app')
.controller("EmployeeCtrl",EmployeeCtrl);
Build the code using Ctrl+Shift+B, the logic.js file will be updated with EmployeeCtrl registered in the Angular Module as shown in the following image
Step 6: To create a View, add the following markup in the index.html
{{empVM.header}}
EmpNo | EmpName | Salary |
{{Emp.EmpNo}} | {{Emp.EmpName}} | {{Emp.Salary}} |
/scripts/node_modules/angular/angular.min.js
http://logic.js
The above html markup shows the Angular directive with databinding.
Step 7: To run the application using index.html file, we will install the http server node package manager. Right click on index.html and select option Open in Command Prompt. This will open the command prompt. Run the following command from the Command prompt
npm install -g http-server
This will install the http server. This is a simple zero configuration command line http server and does good in a development and testing environment.
Run the following command from the same command prompt
http-server
.. to start the http-server on port 8080 as shown in the following image
Open the Browser and enter the following address
http://localhost:8080/index.html
This will show Employee Details as shown in the following image
Step 8: We will modify the IEmployee interface by adding the following method in it (highlighted )
interface IEmployee{
header:string,
Employees:any[];
addEmployee():void;
}
We will change the Employee class by implementing the addEmploye() function as shown in the following code. (highlighted)
//1. The Angular module
var app = angular.module('app',[]);
class Employee{
EmpNo:number;
EmpName:string;
Salary:number;
}
//2. The TypeScript interface
interface IEmployee{
header:string,
Employees:any[];
addEmployee():void;
}
class EmployeeCtrl implements IEmployee{
header:string;
Employees : any[];
Emp:Employee;
constructor() {
this.header = "Employee List";
this.Employees=[
{
"EmpNo":101,
"EmpName":"MS",
"Salary":20000
},
{
"EmpNo":102,
"EmpName":"LS",
"Salary":18000
},
{
"EmpNo":103,
"EmpName":"TS",
"Salary":16000
}
];
this.Emp = new Employee();
this.Emp.EmpNo = 0;
this.Emp.EmpName = "";
this.Emp.Salary = 0;
}
addEmployee(){
this.Employees.push(this.Emp);
}
}
angular.module('app')
.controller("EmployeeCtrl",EmployeeCtrl);
The above code adds a new TypeScript class of name Employee with properties in it. The EmployeeCtrl class declares the Emp property of the type Employee. The constructor of this class instantiates the Emp set toits default values. The EmployeeCtrl class implements addEmployee method, this pushes Employee record in Employees array.
Step 9: Modify the index.html as shown in the following code (highlighted)
/scripts/node_modules/angular/angular.min.js
http://logic.js
The above html markup shows the Angular directive with databinding.
Step 7: To run the application using index.html file, we will install the http server node package manager. Right click on index.html and select option Open in Command Prompt. This will open the command prompt. Run the following command from the Command prompt
npm install -g http-server
This will install the http server. This is a simple zero configuration command line http server and does good in a development and testing environment.
Run the following command from the same command prompt
http-server
.. to start the http-server on port 8080 as shown in the following image
Open the Browser and enter the following address
http://localhost:8080/index.html
This will show Employee Details as shown in the following image
Step 8: We will modify the IEmployee interface by adding the following method in it (highlighted )
interface IEmployee{
header:string,
Employees:any[];
addEmployee():void;
}
We will change the Employee class by implementing the addEmploye() function as shown in the following code. (highlighted)
//1. The Angular module
var app = angular.module('app',[]);
class Employee{
EmpNo:number;
EmpName:string;
Salary:number;
}
//2. The TypeScript interface
interface IEmployee{
header:string,
Employees:any[];
addEmployee():void;
}
class EmployeeCtrl implements IEmployee{
header:string;
Employees : any[];
Emp:Employee;
constructor() {
this.header = "Employee List";
this.Employees=[
{
"EmpNo":101,
"EmpName":"MS",
"Salary":20000
},
{
"EmpNo":102,
"EmpName":"LS",
"Salary":18000
},
{
"EmpNo":103,
"EmpName":"TS",
"Salary":16000
}
];
this.Emp = new Employee();
this.Emp.EmpNo = 0;
this.Emp.EmpName = "";
this.Emp.Salary = 0;
}
addEmployee(){
this.Employees.push(this.Emp);
}
}
angular.module('app')
.controller("EmployeeCtrl",EmployeeCtrl);
The above code adds a new TypeScript class of name Employee with properties in it. The EmployeeCtrl class declares the Emp property of the type Employee. The constructor of this class instantiates the Emp set toits default values. The EmployeeCtrl class implements addEmployee method, this pushes Employee record in Employees array.
Step 9: Modify the index.html as shown in the following code (highlighted)
{{empVM.header}}
EmpNo | EmpName | Salary |
{{Emp.EmpNo}} | {{Emp.EmpName}} | {{Emp.Salary}} |
/scripts/node_modules/angular/angular.min.js
http://logic.js
This modified code has text elements with data bound on them using ng-model directive.
Step 10: Run the http server as explained in Step 7, and view the index.html in the browser, the page will be loaded as shown in the following image
Add values in text boxes and click on Save button, the following result will be displayed
Conclusion: TypeScript provides a OOPs type of experience while working with angular applications. The modular development approach provided in TypeScript along with a transpiler simplifies JavaScript coding complexities.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @
maheshdotnet or connect with him on
LinkedIn