README: Angular 2 has changed significantly since this post was written. As such, please do not use this code verbatim. Instead, focus on the concepts below and then map them to the new syntax and API of Angular 2.0.0.

By now, the cat’s out of the bag on both Angular 2 and Ionic 2. We have a great team working hard on the next big version of Ionic and helping shape Angular 2 in the process. I’m incredibly excited about the progress we’ve made in a short amount of time, and I know the Ionic community is just going to love it.

For many, Angular 2 represents a massive change to the framework they love (or love to hate). Everyone spent so much time learning the odd language of v1 (directive, anyone?), understanding how scopes and digest cycles work, spending time debugging ngModel issues, and trying to figure out the perfect folder structure, and now almost all of that is changing.

Trust me, it’s for the best.

Angular 2 Series

The Ionic team is one of the earliest adopters of Angular 2 for a large project. Because of that, we are learning a lot about the intricacies, limitations, and power of Angular 2. We know that in order to get the community to embrace Angular 2, we need to start sharing our experiences and educating frontend developers on Angular 2.

Starting this week, we are going to do a series of short posts on Angular 2. These posts will cover various parts of the framework, how to use it, and where to get help.

Today, we will start with an intro to the framework, getting everything installed, and trying out the samples.

Getting started

Let’s follow the quickstart guide on the official Angular 2 docs, but with some added color and commentary.

First, create a project folder, and clone the quickstart repo into it:

mkdir myApp
cd myApp
git clone [email protected]:angular/quickstart.git

HTML

Create a new index.html file with this:

<!-- index.html -->
<html>
  <head>
    <title>Angular 2 Quickstart</title>
    <script src="/quickstart/dist/es6-shim.js"></script>
  </head>
  <body>

    <!-- The app component created in app.es6 -->
    <my-app></my-app>

    <script>
      // Rewrite the paths to load the files
      System.paths = {
        'angular2/*':'/quickstart/angular2/*.js', // Angular
        'rtts_assert/*': '/quickstart/rtts_assert/*.js', // Runtime assertions
        'app': 'app.js' // The my-app component
      };

      // Kick off the application
      System.import('app');
    </script>    
  </body>
</html>

Your first response should be, “What’s with all these weird System.* things?” System just adds es6 module loading support to the browser. It’s worth noting, like many of the boilerplate in Angular 2 right now, this is going to be going away (or at least we will abstract it out in Ionic 2, so you don’t ever have to see this). Learned, and promptly forgotten.

Everything else should look pretty familiar, minus the fact that we don’t have an ng-app anywhere.

Javascript

Next, we need to write some ES6!

So, create a file called app.js with this code in it. (the docs use .es6, but I don’t recommend that extension, and it doesn’t seem to be catching on).

import {Component, View, bootstrap} from 'angular2/angular2';

// Annotation section
@Component({
  selector: 'my-app'
})
@View({
  inline: '<h1>Hello {{ name }}</h1>'
})
// Component controller
class MyAppComponent {
  constructor() {
    this.name = 'Alice'
  }
}
bootstrap(MyAppComponent)

The interesting thing about this is how we specify the app component. The bootstrap(MyAppComponent) call tells the app to start, much like ng-app did. Except, in this case, we provided the actual component that starts the app.

Let’s test this!

If you don’t have a local HTTP server installed, we can use npm install -g http-server or python -m SimpleHTTPServer. It’s up to you, but I recommend getting one and learning how to use it.

http-server

Open http://localhost:8080 in your browser, and you should see this:

server

That’s it!

TypeScript?

For the sake of simplicity, the starter project uses a pre-built version of Angular 2 from Traceur.

However, the project is moving to TypeScript right as we speak, which will make the whole toolchain a lot simpler. Suffice to say, you don’t need to learn Traceur or even remember the name for much longer.

Next up: Components

In the file above, we created our first Component. Components are the core of Angular 2, and replace the delicate mess of Controllers, Scopes, and Directives as we knew them from v1.

See the next post in the series, Intro to Angular 2 Components to learn more about the new component system!

Signup for the Ionic Newsletter to get the latest news and updates!

55 Comments

  • Victor Mejia says:

    Nice concise tutorial, thanks! Looking forward to the next posts.

  • lahaxe_arnaud says:

    Very nice article !

  • kunalnagar says:

    I cannot see the article. I just see the heading that’s it. Anyone else?

  • So, is this article so nice and concise that there are no words … ?

  • Shameem Reza says:

    Awesome writing…

  • Andres Felipe says:

    Hey nice way to start, thanks

  • Jim Cummins says:

    Have you guys heard any more info about when Angular 2 will have a router?

    • Bert Vriens says:

      Looking at following g+ post you can already use it. /Start post/
      You can start with ng1 and use the ngNewRouter (which will also be used in ng2) and start with the this.someVariable approach.
      Take a look at my demo-app where I show this approach http://www.annotatedjs.com/notes-app-version-1-0/ with a link to the demo-app.ties this Google+

  • This is such a great idea to write this series to help people get introduced. Really excited to start working with Angular and Ionic 2.

  • blanketwarriors says:

    YAAAAAAAAAAAAAY!!! Thanks for taking the time to write this! Will def check back for more as they come out!

  • Short and Simple article, but through the point and meaningful article. Keep it up…

  • 최종욱 says:

    Great article! Thanks! May I translate this article into korean and share it on my blog? Of course, the post will show the origin(this article)

  • Shahzad Soomro says:

    so short and so clean.. Awesome Tutorial ! Excited to see your next post for TypeScript + AngularJS!

  • BravoZuluMaster says:

    Thanks for the nicely written intro to Ang2.0. It’s much appreciated!

  • Siddhartha R says:

    Cool! Is it possible to get more details in the next blog? For example how would you modify your existing directives into a web-component, your thought process and an example, may be?

  • cihadturhan says:

    Thanks for the tutorial. It’s super simple and understandable. I’d like to see more.

    I have question: In your `app.js` you created a class with a name MyAppComponent but you didn’t declare anywhere that your component belongs to MyAppComponent. How does it know the relation between component and its controller? Does it infer from name like
    my-app + component => MyAppComponent ?

    What if I define two classes like MyAppComponent1 and MyAppComponent2 in app.js? Which one will it choose?

    • ironmonk says:

      The “@Component” declaration is an annotation for the component class that has the selector “my-app” which tells the component where to find elements.

      • Bo83 says:

        So to clarify, the “@Component” and “@Template” attributes will always apply to the class body that is defined immediately below them, is that a true statement? Thanks!

  • wahyd4 says:

    Awesome team!

  • Elias Hansén says:

    Thanks for the introduction! Will be following along with the series 🙂

  • awesome, so simple that it’s even better than the official one !

  • Ryan Lindgren says:

    Please don’t go crazy with the abstraction, on your end.

  • Ronan Connolly says:

    Very succinct thanks 🙂

  • Mangap says:

    Any estimate time when it will be released?

  • opportunex says:

    When are you releasing Ionic 2? Is it going to be backward compatible? Having just spent the last three months learning Angular and Ionic, this seems a bit disconcerting. As a veteran jQuery and JavaScript programmer, I found Angular to have a very steep learning curve and the prospect of having to do all of that over again is a stressful prospect.

    Our app is nearly ready for release and all of this makes me wonder if we selected the right platform for the job. Any thoughts?

    • yesimahuman says:

      We are targeting for later this year. In the meantime, we are going to be talking about ways to naturally move to 2. Today, we recommend a few things: use component-style directives (restrict: E), and use services. Try to limit your use of scope and controllers.

      The good thing is these are all best-practices in Angular 1 anyways, so you’ll have a more natural update path.

      Also, many of the directives are staying the same, so the markup you write won’t be dramatically different. We are also thinking of an automated 1to2 tool as well.

      The benefit to 2 is really that it’s a lot easier to learn and use than 1 was. It will make it easier to have your whole team help on the app, rather than just a hardcore angular person.

  • Max says:

    Trying the exact code in this post I get an “Error during instantiation of Token(AppView)!. ORIGINAL ERROR: Error: No template found for MyAppComponent” message…

    P.S.: if I export the class, nothing happens

  • Krish says:

    I could not run this example. I have used the same structure and deployed to tomcat server. Should I require any special browser to support ES6 scripts? Any idea how I could proceed?

  • Arash Bizhan zadeh says:

    Why TypeScript? Isn’t Dart a natural choice if they wanted a alternative language.

  • Dmitri says:

    So how is this better or easier than simply putting
    ‘Hello {{ name }}’
    into your HTML and declaring `name`
    in the controller exactly the same way?

    No verbose markup keywords like “@View”, “@Component”, etc, to remember, less code to write and maintain, anything I am missing?

  • Nemo says:

    should I really be starting a project on Ionic now?? which uses Angular 1.x…. seeming that Angular 1 et 2 are so different from each other I don’t think my company can afford the resource to maintain 2 version of a same project..

  • Hassan Moujahed says:

    Nice article but, it does not work for me i have 2 errors:
    Uncaught SyntaxError: for-in loop variable declaration may not have an initializer

    inUncaught ReferenceError: System is not defined file es6-shim.js line 4941

  • gnana sekaran says:

    I got an error, please help me!!
    Uncaught ReferenceError: System is not defined

  • 陳仲仲 says:

    the best article about angular2 hello world!! Thanks ionic team’s passion and this awesome job!

  • Gabriel D says:

    Where should index.html and app.js should be placed? Inside any folder? Or on the root of the project? I added on the root, but it did not work

  • AlexH says:

    Nice. I plan to star my series on angular 2 too
    Time to start playing with Angular 2.0

  • Áron Barócsi says:

    I mean even ionic 1.x is full of bugs and many issues coming from bad principles, Ionic github is totally overwhelmed with open tickets and unfixed bugs and now you are working on ionic 2. This is good, but why not work on ionic 3?

  • Jay Moss says:

    has the repo been locked down or moved:

    ..myApp>git clone [email protected]:angular/quickstart.git

    Cloning into ‘quickstart’…

    Permission denied (publickey).

    fatal: Could not read from remote repository.

    Please make sure you have the correct access rights

    and the repository exists.

    • Arman Fazylov says:

      Had the same issue. First generate ssh key for your github account (i called it github_rsa), then upload it to your github. Then run following commands from terminal:
      ssh-agent -s
      ssh-add ~/.ssh/github_rsa

  • earl8888 says:

    什么时候可以出中文版的?

46 Trackbacks