Angular 2 by Example
Let's start with what Angular 2 is:
- A framework to build client-side applications
- Has an expressive template language
- Powerful data binding
- Available as release candidate 4 (07/26/2016)
Okay, so another client-side framework for single page applications, but why?
- Fixes many performance pitfalls of Angular 1
- Modern design using ES6 features, e.g.: Classes, Template strings
- Simplified API and clearer concepts
- Uses Typescript as the primary language for: Interfaces, Type declarations, Decorators and Annotations
For the SPQR app, we use a very simple project structure.
- We use System.js to load ES6 based modules
- Also Webpack or browserify can be used
- Typescript since it is the recommended language
- Hosted on Plunker (http://plnkr.co/)
The building blocks of an Angular2 app
Components are the central abstraction of Angular2. They are comprised of the template as well as controller methods and properties.
Of course, the heart of every MVC framework is its templating, i.e. describing how data is rendered. Angular2 supports three types of data binding:
The control flow of when and how often data is output is controlled via structural directives.
Structuring application logic
The main part of the business logic usually resides in services. They encapsulate functionality that is used across many components.
To access simple formatting and transformation routines from the templates, pipes are used, e.g. to format a date.
Routers are used to control the flow through the application with meaningful URLs and a history.
Routing is either triggered programmatically or by using routerLink instead of hrefs.
Components can subscribe to route changes to handle transitions more efficiently than redrawing the whole app.
Extending the behaviour of HTML
Directives are the most scary concepts of Angular.js 1. In Agular2 they got way simpler. Directives are a clean and easy way to extend HTML with new elements or attributes.
Model data can be the input of a directive.
And the directive can also output data, e.g. as events.
Two-way binding with directives is just a combination of an input and an output. Note, that the output property must have the same name as the input property with an appended change to work properly.
See these concepts in action!
Now that you've seen all building blocks of Angular2 (Components, Pipes, Routers, Services, Directives), have a look at the SPQR app in Plunkr.
On the left you have all the project files, i.e. the components, the HTML etc. On the right you can directly play with the code and see the results.