This document discusses Angular 2 and summarizes Ross Dederer's presentation on migrating an application from Angular 1 to Angular 2. Some key points covered include:
- Angular 2 is more modular, modern, component-based and uses TypeScript.
- Components provide better encapsulation and Angular 2 is simpler and more performant than Angular 1.
- Migrating involves converting code to TypeScript, keeping the MVVM pattern, and porting the viewmodel/component and view.
- The presentation demonstrates migrating a sample application that uses Wijmo controls from Angular 1 to Angular 2.
2. about: me
Ross Dederer
Developer Relations of Wijmo
We sell JavaScript UI controls
o Grids
o Chats
o Inputs, etc
Always researching new frameworks
3. about: discussion
What is Angular 2 – sharing experiences
TypeScript
o Introduction
o Comparison to JavaScript
Data Services Quick Start Application
Type Safety
Data Binding
Migrating View to Angular 2 template
5. Angular 2 introduction
Modular
o Smaller Core
Modern
o Evergreen browsers using ECMA 6
Component Based
TypeScript
o Transpiling
Documentation has two tracks
Google will continue developing Angular 1.x
6. Angular 2 – first impressions
Better Encapsulation – Components
Better Performance – fast initial loads, server side pre –rendering, faster change
detection
Angular 2 is actually simplier than Angular 1
o Delegates tasks to JS interpretor.
o Leverages HTML5 more efficiently
Typescript Integration
8. TypeScript
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
Open Source
Find errors at design time
9. Transpilation
Source to source compilation
o Creates a map file
Why is it needed?
o Modern browsers cant understand TS
Built into Visual Studio
10. IntelliSense
Feature of TypeScript
o Not exclusive to Angular 2
C# developers utilize it heavily
Self documentation
Self documentation
11. Module
Application is a collection of Modules
Optional – but recommended
o Need to us TypeScript ( ES2015 )
Angular provides us built in modules
export class PortingFromSL{
}
import {PortingFromSL} from
'./app';
import {Component,View} from
'angular2/core';
12. Component
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 destroyes components
13. Templating
Components View contains component Template
A form of HTML ( not a HTML Form )
Angular manages the component and its view ( template )
All HTML is valid Template Synatx
15. Data Binding
Interpolation {{ }}
Template Expressions [property]=“expression”
o Produces a value
Template Statements (event)=“statement”
o Responds to event
Two-way Data Binding [(target)] = “expression”
16. Data Services QuickStart Application
Loading Data into 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
Live Demo: http://demos.wijmo.com/5/Angular/PortingFromSL/PortingFromSL/
18. Wijmo Controls used
Wijmo.core
Wijmo.grid
Wijmo.input
o Input number
o Input date
o Combo box picker
Binding to all available control properties
Two-way binding to properties
Event Bindings
Bindings for ngFor
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 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
21. Migration from Angular 1 to Angular 2
Convert JavaScript to TypeScript
Keep familiar MVVM development pattern
Porting the ViewModel - Component
o No controller?
o No $scope?
Porting the View
o New attribute syntax
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';
Made my life really easy
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
*ngFor
In Angular 1
Ng-
click=“someEvent()”
In Angular 2
(click)=“OnSave()”
<div *ngFor=“#qh of QueryResources, #index =index”> {{index}} {{qh.table}}
</div>
In Angular 1
Ng-
click=“someEvent()”
In Angular 2
(click)=“OnSave()”
<div *ngFor=“#qh of QueryResources, #index =index”> {{index}} {{qh.table}}
</div>
So this is what the app looks like that we will be demoing today
If you are interested in learning more about the silverlight to MVVM HTML5 conversion I encourage you to check our Migrating to MVVM and HTML webinair.
We are literally using the same back end here for our Ng1 sample and our Ng 2 sample. So if you look in the silverlight code, you should see the same oData connections in our Angular 2 application, which is a great help and it made life a lot easier for me.
This was nice because this sample uses HTML5 so it can run virtually anywhere unlike the original silverlight sammple. So today we are going to continue that migration story.
Simply put: Angular 2 is a framework. You can use it to help build client applications in HTML and JavaScript.
Today I am going to show you how to build a component and along the way I will cover other topics. Lets talk about what a typical Angular 2 application procress would look like.
We write applications by composing HTML templates with Angular markup, adding component classes to manage those templates, adding application logic in services, and handing the top root compoennt to Angulars Bootstrapper.
In this talk today, I will cover all of these high level topics in the talk.
Angular is broken down into eight main building blocs , module, component, template, metadata, data binding, services, directives, and finally dependency injection. A few of these are outside the scope of my migration application
Angular 2 documentation is broken down into two 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
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.
Before we get too carried away with Angular 2 I want to spend some slides talking about and introducing Typescript as I will use Typescript in my sample instead of Javascript.
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.
You can use NodeJS to install the Typescript compilier if you want its just
Npm install –g typescript
However, I personally like to use VisualStudio for development which Typescript is supported in VS 2013 v2 and above
Additionally, 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. I have some screen shots in a later slide that will show you guys what I am referring too.
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. So lets talk a little bit about what is going on here
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. Usually a module will export one thing such as a class. In our demonstration I will show you that we are actually going to be exporting a class.
Here in the center of the slide you will see a code snip from our application that tells TypeScript that this is a module whose PortingFromSL class is public and accessible to other modules of the application.
Below that you will see an import statement, this import statement tells the system it can get PortingFromSL from a module found in our app.ts file. You will note that we are using the relative file paths
In practice the module name is often the same as the filename without its extension. So as you will see in the demo we will call our module app.ts
Modules can be libraries of other modules but that is outside the scope of the discussion today.
Angular2/core in the beta version or angular2/angular2 if you are working with Alpha, are the primary libraries which contain most of the things we need. It turns out we can import this base library in the same way that we would import our custom classes or modules.
So if we want to create a component with a view we will need to import the following libraries into our PortingFromSL module. The syntax should look familiar.
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.
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 eastate 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 quickstart 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. Addtionally, 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, althought his is a simple application, I will not spend to much time discuess 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 and @view so we can keep it simple.
Up until this point we have really only talked about a class, Angular is still a bit unsure. 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
The first data binding I want to discuss is Interpolation because it should already look familiar. In fact, it is pretty similar to what you saw in Angular 1.
Interpolation is used to place strings into text between HTML element tags and within attribute assignments. Usually the items between the {{ }} is the name of the component property. Of course we evalutate expressions as well, such as 1+1
A template expression produces a value. Angular executes the expression and assigns it to a property of a binding target; the target might be an HTML element, a component, or a directive.
The next process is a template statement that respondes to an event raised by a binding target such as an element, component, or directive. Think of this as having a side effect, It’s how we update application state from user input.
This first two are one-way from data source to view target. So these would be properties, attributes, classes, or styles.
The third one, template statements one-way from view target to data source. This will be used for an event.
So in conclusion
Data binding is a mechanism for coordinating what users see with application data values. While we could push values to and pull values from HTML, the application is easier to write, read, and maintain if we turn these chores over to a binding framework
One note though, all of these ways are also supported in the canonical form. i.e. you can but bind- infront of everything if you choose to not use the parens or brackets
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.
Due to the fact that Silverlight isnt supported in most browsers or that most people havent updated their silverlight in awhile, I provided a screen show of the the original application so you can see what it looks like loading in a browser. Note that this app would not work on mobile devices that do not support Silverlight.
We are going to move this over to Angular 2 and move it to HTML5 and bootstrap so this application will load nicely on a mobile platform as well as desktops.
Additionally, I will show you how you can use Angular 2 templates to build that second grid that shows the connection requests. This is a cool little feature microsoft added to the sample so you can make sure that all of your data is coming across correctly. If you click on those blue hyperlinks it will show you the JSON string that is returned.
To begin, lets talk about how we are going to structure this application and do a comparison between Ng 1 and Ng 2
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.
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.
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.
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 arbitray 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