This document discusses migrating from Angular 1 to Angular 2. It provides an overview of Angular 2 including its modular and component-based architecture. It also discusses TypeScript and how it is used with Angular 2. The document then walks through migrating a sample Silverlight application to an equivalent Angular 2 application, covering converting the viewmodel to a component and porting the view. It emphasizes keeping a similar MVVM pattern and discusses new Angular 2 concepts like templates, metadata and bindings.
2. about: me
Ross Dederer, Developer Relations
Wijmo specializes in JavaScript UI controls
o Grids, FlexSheet
o Charts, Financial Charts, Gauges
o Inputs, etc
o OLAP
Supported AngularJS since the early days and now offer full Angular 2 support.
Wijmo Team always researching new frameworks
o React and Ember coming soon
3. about: discussion
What is Angular 2?
TypeScript
o Introduction
o IntelliSense
Angular 2: 8 Building Blocks
Data Services Quick Start – Migration Story: Silverlight to HTML5
Migrating View to Angular 2 template
Migrating ViewModel to Angular 2
6. Angular 2: introduction
Modular
o Smaller Core
Modern
o Evergreen browsers using ECMA 6
o Legacy Browsers supported
Component-Based
Developed using TypeScript
Documentation has two tracks
Google will continue developing Angular 1.x
o Wijmo will continue to support it
7. TypeScript: introduction
TypeScript was created by Microsoft ( FOSS )
Google is fully adopting TypeScript for Angular 2 development
Superset of JavaScript that compiles to plain JS
o Any browser, any host, any OS
Offers classes, modules, and interfaces
Object-Oriented with Classes, etc.
Type Safety
Find errors at design time
8. IntelliSense
Feature of TypeScript
o Not exclusive to Angular 2
Familiar experience for experienced C# developers
Self-documentation
9. Angular 1 vs. Angular 2: Visual Studio
Angular 1
JavaScript
Angular 2
TypeScript
10. Angular 2: first impressions from Wijmo devs
Better Encapsulation – Modular Design
o Components
Angular 2 seems more natural than Angular 1
o Delegates tasks to JS interpreter.
o Leverages HTML5 more efficiently
Typescript Integration
o IntelliSense
No $scope or $watch
12. Module
Application is a collection of Modules
Angular provides us built-in modules
Dedicated to single purpose
Expose “things” – classes, functions, values
o Other modules import these “things”
import {PortingFromSL} from './app';
import {Component} from 'angular2/core';
export class PortingFromSL{ }
13. Component
Define a module as component by attaching Meta Data to plain old TS class
Controls patch of screen – View
Contains our class that interacts with the view
o Via API of properties and methods.
Each Component has a companion Template
“Code-behind” for components View
Angular creates updates and destroys components
14. Templating
Components templateUrl contains component Template
A form of HTML (not an HTML Form)
Introduces new syntax
o *ngIf , *ngFor
Angular manages the component and its view (template)
All HTML is valid Template Synatx
15. Metadata and Decorators
Decorators
o @component
Metadata
o Selector
o TemplateUrl
o Directives
o Providers
The template, metadata, and component together describe the view.
16. Data Binding: overview
Interpolation {{ value }}
Template Expressions [property]=“expression”
o Produces a value
Template Statements (event)=“statement”
o Responds to event
Two-way Data Binding [(target)] = “expression”
18. Data Services Quick Start Application
Loading data into Wijmo CollectionView
o Sort, filter, group
Managing hierarchical data to reflect current state
o Master Detail Relationships
Binding data to Wijmo controls
o Line of business application template – Grid’s inputs
Live Demo: http://demos.wijmo.com/5/Angular/PortingFromSL/PortingFromSL/
19. Application Structure: new things
In Ng 1, we needed to create a new app and give it a controller to
handle all of the business logic.
o No more controllers in Ng 2
In Ng 2, we will organize our app inside a module component that
we will call PortingFromSL
o We will leverage the benefits of TypeScript here
In Ng 2, we will move all of our markup and templating sits in
app.html
In Ng 2, we need to introduce a root component loader
20. Migration from Angular 1 to Angular 2
Convert JavaScript to TypeScript
o Not required but I recommend it
Keep familiar MVVM development pattern
Porting the ViewModel — Component
o No controller?
o No $scope?
Porting the View
o New attribute syntax
21. Bootstrapping - Launching Application
From bootstrap.ts :
import {class} from './app';
bootstrap(class.component);
Inside default.htm:
System.import(“/src/class.component”);
22. Porting the Model
We luckily will use the same model/Datasource
o JSON coming from service can serve as model.
private _svcUrl: string = 'http://services.odata.org/Northwind/Northwind.svc';
23. Porting the ViewModel
CollectionView objects for Customers, Orders, Details
Load some data using AJAX
Ng 2 More closely related to SL than NG1
Class App
customers: wijmo.collections.CollectionView; // or any
Constructor
this.customers = new wijmo.collections.CollectionView();
24. Porting the view: html
New Template Syntax
Updated Bindings
Need to add placeholder in default.html
In Angular 1: In Angular 2 :
25. Porting the view: wijmo controls
Angular 2 code:
New Binding syntax
New Template syntax
Local Variables
26. Migrating the ‘Controller’
export module portingFromSL {
@Component({
selector: 'app',
templateUrl: 'src/app.html',
})
export class App {
// business logic
}
29. Conclusion
Read more at:
o www.wijmo.com/angular2
o Angular.io
Contact me at ross.dederer@grapecity.com
Notas do Editor
Hello Everyone, welcome to the GrapeCity webcast; How to migrate an application from Angular 1 to Angular 2
So for today, I want to cover..
Here is a screenshot of what the original application looked like in Silverlight. You can see we have all the basic Line of Business behavior but what this is really lacking is portability. You need to install an SDK to get this to run in your browser and it will not work on Mobile devices. About a year or two ago we ported the Silverlight application over to HTML5 and AngularJS.
Today, I want to continue this migration story and take our HTML5/AngularJS sample and port it to more improved Angular 2.
So this is what the app looks like that we will be demoing today.
< Go to Visual Studio and show the sample running >
So before we begin migrating, lets talk about what Angular 2 is. Simply put: Angular 2 is a framework. You can use it to help build client applications in HTML and JavaScript or Typescript.
<Click through>
Angular 2 is modular by design. Groups of coordinated components divide the responsibilities of our application.
Angular 2 is a very modern framework. I will not get into all of the details today but Angular 2 uses optimization techniques for performance such as server side pre rendering.
Angular is broken down into eight main building blocs , module, component, template, metadata, data binding, services, directives, and finally dependency injection.
Angular 2 documentation is broken down into two learning tracks, one fore Typescript learning and one for JavaScript learning. For my migration and for the rest of the talk, we will stick with the Typescript track.
Google has announced that they will continue supporting Angular 1.x and Wijmo will do so as well.
Typescript is a programing language developed and maintained by Microsoft and is provided free and open source. Anders Hejlsberg ( halls-burg ) is the founding father of not only Typescript but C# as well, so it should look familiar for those coming from a .NET c# background.
Google has announced they are fully adopting TypeScript for their Angular 2 development which is pretty cool.
I personally like to use Visual Studio for development ; of which Typescript is supported in VS 2013 v2 and above.
If you aren't a windows user and are looking for an alternative to Visual Studio, you can use NodeJS to install the Typescript compiler if you want: its just
Npm install –g typescript
A nice feature of TS is that we can find errors in our application and logic at design time as opposed to at run time. Finding errors at runtime can sometimes either be too late or difficult to address.
If you have never worked with TS before, its okay, its easy to pick up and learn if you already know JS. In fact, at run time, your TS that we write will be transpiled, using babble or web pack or something like this, into pure JS to run in browser.
Typescript is going to offer us the ability to use classes, allow for type safety, and better be bugging.
Typescript itself is being adopted more and more for large scale enterprise development
So after running through the documentation and playing around with the quick start guides I made a list of some of my first impressions and borrowed some from our development team here at Wijmo.
At first glance I noticed the seperation of concerns.
Angular2 itself doesn’t require a modular approach but it is recommended. As we said though for this webcast we will be using TypeScript and adopting a modular design approach.
Components are the unified mechanism for creation of any part of an application, from the application itself, to separate pages, to small UI controls. If you know how to create one of them then you immediately know how to create the others. By using Components you force yourself to create self-sufficient parts that are automatically ready for reuse.
I will demo this later but creating a component in Angular 2 is very simple, all we need to is add a Component Decorator to our TypeScript class and we can access it from our markup.
Angular2 just seems more natural, from a coding standpoint, than Angular 1 or even other frameworks like Knockout. In Angular2 we don’t need to have ko.observable or $scope wrappers all over the application.
No more “scope”. The “scope” object present in Angular 1 is gone in Angular 2. This special variable existed mostly to enable change tracking, with its “$watch” and “$apply” methods. It is no longer needed;
Here is an imagine from Googles documentation. It does a good job showing you the role each building block does.
You can see on the left hand side we have our module components and module services.
Below that we are going to have our injectors that inject a service. For this demonstration today, I did not use a Data service to get our data so I will not be referring to services and injectors to much during the rest of the discussion. Once we have our component built you will see its very easy to add an injector or service.
We will, however, spend some time working with Templates, metadata, and Components. After we have discussed some templating and componentes, I will walk you though property and event binding and show you how I use it in my application.
What do we mean when we say Transpilation. What we are referring to is source to source compilation which means that we are going to take the source code of a program written in one programming language as its input and output the equivalent source code in another programming language.
Rest assured though knowing that if you get an error in your Javascript at runtime, you can use the map to go look where in your TypeScript file that error is coming from. Otherwise your breakpoints aren’t going to make any sense when you are debugging something at run time.
We are basically staying at the same level of abstraction. An example of this would be something like Pascal to C.
You might begin to notice that our Typescript looks like C# code.
Looking like C# though is not enough to convince C# developers to pick up TS and start developing. C# developers like to use built in tools such as IntelliSense. Well, luckily TS, unlike JS, supports IntelliSense.
A module should be dedicated to a single purpose, generally exporting one thing such as a class.
This is from the documentation but I think they did a good job summarizing the take aways here
Angular apps are composed of modules
Modules export things – classes, functions, values – that other modules import
We prefer to write our application as a collection of modules, each module exporting one thing.
For our example today, we are only going to export components. if we want to create a component we will need to import the component library into our module. The syntax should look familiar.
We define a Component's application logic - what it does to support the view - inside a class. The class interacts with the view through an API of properties and methods.
Think of a component as something that controls a patch of screen real estate which we and the Angular team will call a View. Most everything the user sees will be a view controlled by a component.
Each component has a companion template, we will be demoing this in our quick start application.
Angular is going to create, provide updates, and destroy components as the user moves through the application.
The component comprises of two core parts:
Typescript class which has a ts file extensions, implements the model and controller and exposes properties and events that can be used in the view. Think of it as a code behind for the components view
The second core part is the view itself, implemented in an HTML file. This defines the look of the component. Additionally, as I will demo I will show some event and properties bindings as well.
This is outside the scope of the demonstration today but we can use Components to provide the whole SPA application look, with nav menus and a special place where current page should be shown and provide additional application routing, although his is a simple application, I will not spend to much time discussing routing
We will get into decorators and metadata selectors when we get to the demo
We will need to define a components view with its companion template. A template is a form of HTML that is going to tell Angular how to render the component.
Templates will generally look like HTML but as we will see in the sample, we will introduce some new syntax in the demo.
Many of us are already familiar with component/template duality from our experience with MVC and MVVM. In Angular, the component plays the part of the controller/viewmodel, and naturally the template represents the view.
Almost all HTML syntax is valid template syntax. The <script> element is a notable exception; it is forbidden, eliminating the risk of script injection attacks. Obviously some tags are not very helpful such as body and html so you probably wont see them in practice
We can extend the HTML vocabulary of our templates with components and directives that appear as new elements and attributes.
Before we can migrate our view in our application, we need to talk about some new data binding and accessing the DOM.
The second to last building block that I wanted to cover today is MetaData Luckily in our application I only used @component so we can keep it simple.
Up until this point we have really only talked about a class, Angular is still a bit unsure what to do with a TypeScript class. Its not a component untill we attach some metadata to the class. The easiest way to attach metadata in TypesScript is with the decorator.
This is going to go before we define our class. Think of a decorator as a function that can have configuration properties. For today we are going to focus on templateUrl and selector
selector - a css selector that tells Angular to create and insert an instance of this component where it finds a <hero-list> tag in parent HTML. If the template of the application shell (a Component) contained
<hero-list></hero-list>
Angular inserts an instance of the HeroListComponent view between those tags.
templateUrl - the address of this component's template which we showed above.
directives - an array of the Components or Directives that this template requires. We saw in the last line of our template that we expect Angular to insert a HeroDetailComponent in the space indicated by <hero-detail> tags. Angular will do so only if we mention the HeroDetailComponent in thisdirectives array.
providers - an array of dependency injection providers for services that the component requires. This is one way to tell Angular that our component's constructor requires a HeroService so it can get the list of heroes to display. We'll get to dependency injection in a moment
I saved the best for the last. Data Binding is key to Angular 2, without a framework handling it, we would be responsible for pushing and pulling data values into the HTML controls, as well as responded to events. Data Binding is a mechanism for coordinating parts of a template with parts of a component.
There are four forms of Data Binding, each having a direction as indicated by the errors in the picture.
The first is interpolation, which may be familiar to us from our early days of AngularJS development. We can use it to place calculated strings into text between HTML tags and attribute assignments.
The second follows the same direction and is referred to as Template Expressions.
The third is Template Statements. These respond to an event raised by an element, component, or directive. Think of this binding as one that has a side effect, its how we update application state based on user input.
The forth and final mechanism is a one that combines property and event binding in a single notation.
When we get to visual studio I will show you all this in the code but I wanted to walk you through what exactly we are doing in this application if you have not seen it before.
To begin we will load some data from the Northwind data source and build three separate collection views, one for customers, orders, and a union of the too we called details. We are going to load these into the Wijmo collectionVIew so that the CollectionView will handle pagainating our data, sorting, filtering, and keeping track of the current selected Item.
The application will load a list of customers, when the user selects a customer, the app displays the orders placed by that customer. As the user naviagates around the controls the state of the application will change. For example, when a user selects a customer, the app will display the orders placed by that customer. Additionally, when the user selects an order, the app displays the orders detail. The type of master-detail relationship is another common feature of MVVM apps.
Finally, we will bind some data to our controls. The combobox control provides customers and orders. Textbox controls to provide order information, and finally a datagrid to show orders details. We picked these three controls because most line of business applications utilizie some sort of combo box, input box, and data grid.
The original source from Microsoft is still available online.
To begin, lets talk about how we are going to structure this application and do a comparison between Ng 1 and Ng 2
There are a few languages out there that really enable you as a developer the ability to develop better large scale applications. A few of which are TypeScript, CoffeeScript, and PureScript.
For today, we are going to use TypeScript for many reasons. The first of which is static type, and modules and classes. Which makes the language a strongly type langauge. It is easier to learn because it is a superset of JavaScript. The current version of Angular 2 is being developed in TypeScript and we are traditionally Microsoft VisualStudio users and Typescript has many built in features in more modern VS environments. Its worth noting here that there are many freely available resources out there to learn TS. I will talk more about this later. At the end of the day, simply put, TS compiles into JS
After we have finished porting the ViewModel I will show you some key things that are not included in the Ng2 app that you may be finding yourself looking for if you are used to Ng1 like scope or controllers.
Finally, I will show you how we will be handling our view, it is slightly different than the approach in Angular 1 and Ng 2 has introduced some new data binding features as well as templating syntax.
In the next slides I will show you how to migrate a simple plain html element to work well with your Ng 2 bindings as well as demo how you can utilize wijmo’s controls as we fully support their new bindings.
This is not Bootstrap, the twitter CS/JS framework but Angular Bootstrap. In Angular 1, we would tell angular to bootstrap a file if it saw ng-app in the html or body tags. You could from there define your applciation a controller. You could reuse that controller across other ng-apps . That controller will then provide you everything inside the scope. For example, you could assign a controller to body or to a simple div. If you are familiar with Ng2, you will see that this is no longer required in our default.htm page. We will define our Ng2 components as elements not as attributes of elements, if that makes sense.
Instead we are going to use SystemJS to load in a bootstrap file that will contain everything Angular 2 needs to now to get up and running.
We will need to do two things to actually run the application, the first is to call Angulars browser bootstrap function and then pass it it our application root component that we just wrote. Here the code more generic, I will show you specifically what I had to do in my code later during the demo section, but you should be able to follow this syntax when building your own application.
Here we are going to create objects for customers, orders, and details. Due to screen reel estate I just put customers on the slide but I will show you the code as well.
We are going to use AJAX to load some data into these collectionsViews and then build our details collectionView based on user input.
In our class definition you will see that we are going to define customers as a wijmo.collections.CollectionView type. This will expose every thing to us in intellisense when we reference customers later in the application. If we arent sure what type to use, maybe its because we are earlier on in our migration phase, we can simply assign any here and Angular will not enforce strong types. Finally we instaniate a new collectionView in our default constructor.
Angular 1 offered us over 70 built in directives and of course the community added many more many people in this room have probably even written their own private directives.
In Angular 2 we can achieve the same end result without needing all of those special directives due to the more advanced binding system.
Lets look at an example on the right hand side of the screen.
Of course, there still are some built-in directives to solve complex tasks. And of course we will still need to write some of our own directives.
For today, I am only going to focus on the template syntax that we are going to use in the demo
ngFor is a repeater directive that we did not have in Angular 1. This allows us to present a list of items. This allows for a literal reading.
So this literally means: Take each JSON object in the QueryResources array, store it as a local qh variable, and expose it to the grid. Additionally we capture the index so we can make a list 1-x.
If your curious where the # sign came into play, this is us just creating a local template variable. Applications are constructed as a tree of component instances, with easy access to each instance. By marking a component element in markup with a local template variable (e.g. #var) you get access to its instance with all its properties and methods that can be used in both markup binding expressions and TypeScript code.
Finally we use interpolation to display the current index and a link to the JSON data
There are many more but I am only foxuing on the ones we are using today.
Lets take a look at what our Default.html would look like in an Angular 2 application. Everything will appear normal until you see our app-cmd tag. The tag is going to represent a root application component. Our demo today will only have one component. All the sample life happens inside this component, and default.htm is used solely to add this component and bootstrap the application in this way.
Think of a component as a single unit which is a model, a controller, and a view.
In Angular 2, everything is a component, be it the application itself or parts like a wijmo control.
In Angular 1, the developer has full freedom to define views and controllers seperately, and combine them in an arbitrary manner. The developer can use the controller across muliptle views as necessary. In Ng 2, we cant define them separately and combine them as needed, we need to utitilize Typescript class inheritance capability. If you are interested in learning more about this concept, I would encourage you to check out our explorer sample