docs(Dart): sync with TS version of quickstart (#2828)

* update cache

* docs(Dart): sync with TS version of quickstart

* sync cache with updates from previous commit
This commit is contained in:
Patrice Chalin 2016-11-18 13:23:38 -08:00 committed by Filipe Silva
parent f2daab7a9e
commit 0fa21c49ad
3 changed files with 386 additions and 627 deletions

View File

@ -41,8 +41,11 @@ block install-packages
packages (along with the packages they depend on).
code-example(language="sh" class="code-shell").
&gt; <span class="blk">pub get</span>
Resolving dependencies...
pub get
block create-your-app
:marked
Let's create a folder to hold our application and add a super-simple Angular component.
block annotation-fields
:marked
@ -57,6 +60,10 @@ block create-main
li a #[b folder named #[code web]]
li a <b>file named #[code #[+adjExPath('app/main.ts')]]</b> with the following content:
block commentary-on-index-html
:marked
Note the `<my-app>` tag in the `<body>`, this is *where your app lives!*
block run-app
p.
We have a few options for running our app.
@ -76,83 +83,85 @@ block run-app
Once the app is running, the browser window should show the following:
block build-app
.alert.is-important
:marked
If you don't see **My First Angular App**, make sure you've entered all the code correctly,
in the [proper folders](#wrap-up),
and run `pub get`.
.l-verbose-section#section-angular-run-app
:marked
### Building the app (generating JavaScript)
Before deploying the app, we need to generate JavaScript files.
The `pub build` command makes that easy.
code-example(language="sh" class="code-shell").
&gt; <span class="blk">pub build</span>
Loading source assets...
:marked
The generated JavaScript appears, along with supporting files,
under a directory named `build`.
#angular_transformer
h4 Using the Angular transformer
p.
When generating JavaScript for an Angular app,
be sure to use the Angular transformer.
It analyzes the Dart code,
converting reflection-using code to static code
that Dart's build tools can compile to faster, smaller JavaScript.
The highlighted lines in <code>pubspec.yaml</code>
configure the Angular transformer:
- var stylePattern = { otl: /(transformers:)|(- angular2:)|(entry_points.*$)/gm };
+makeExample('quickstart/dart/pubspec.yaml', null, 'pubspec.yaml', stylePattern)
p.
The <code>entry_points</code> item
identifies the Dart file in our app
that has a <code>main()</code> function.
For more information, see the
<a href="https://github.com/angular/angular/wiki/Angular-2-Dart-Transformer">Angular
transformer wiki page</a>.
.l-sub-section#performance
h3 Performance, the transformer, and Angular libraries
p.
When an app imports <code>bootstrap.dart</code>,
it also gets <code>dart:mirrors</code>,
a reflection library that
causes performance problems when compiled to JavaScript.
Don't worry,
the Angular transformer converts the app's entry points
(<code>entry_points</code> in <code>pubspec.yaml</code>)
so that they don't use mirrors.
#dart_to_js_script_rewriter
h4 Using dart_to_js_script_rewriter
:marked
To improve the app's performance, convert the
HTML file to directly include the generated JavaScript;
one way to do that is with `dart_to_js_script_rewriter`.
To use the rewriter, specify `dart_to_js_script_rewriter` in both
the `dependencies` and `transformers` sections of the pubspec.
- var stylePattern = { otl: /(dart_to_js_script_rewriter.*$)|(- dart_to_js_script_rewriter.*$)|(dependencies:)|(transformers:)/gm };
+makeExample('quickstart/dart/pubspec.yaml', null, 'pubspec.yaml', stylePattern)
//- Remove details of building from QS for now. (It is too early for these details.)
if false
.alert.is-important
:marked
The `dart_to_js_script_rewriter` transformer must be
**after** the `angular2` transformer in `pubspec.yaml`.
If you don't see **Hello Angular!**, make sure you've entered all the code correctly,
in the [proper folders](#wrap-up),
and run `pub get`.
:marked
For more information, see the docs for
[dart_to_js_script_rewriter](https://pub.dartlang.org/packages/dart_to_js_script_rewriter).
.l-verbose-section#section-angular-run-app
:marked
### Building the app (generating JavaScript)
Before deploying the app, we need to generate JavaScript files.
The `pub build` command makes that easy.
code-example(language="sh" class="code-shell").
&gt; <span class="blk">pub build</span>
Loading source assets...
:marked
The generated JavaScript appears, along with supporting files,
under a directory named `build`.
#angular_transformer
h4 Using the Angular transformer
p.
When generating JavaScript for an Angular app,
be sure to use the Angular transformer.
It analyzes the Dart code,
converting reflection-using code to static code
that Dart's build tools can compile to faster, smaller JavaScript.
The highlighted lines in <code>pubspec.yaml</code>
configure the Angular transformer:
- var stylePattern = { otl: /(transformers:)|(- angular2:)|(entry_points.*$)/gm };
+makeExample('quickstart/dart/pubspec.yaml', null, 'pubspec.yaml', stylePattern)
p.
The <code>entry_points</code> item
identifies the Dart file in our app
that has a <code>main()</code> function.
For more information, see the
<a href="https://github.com/angular/angular/wiki/Angular-2-Dart-Transformer">Angular
transformer wiki page</a>.
.l-sub-section#performance
h3 Performance, the transformer, and Angular libraries
p.
When an app imports <code>bootstrap.dart</code>,
it also gets <code>dart:mirrors</code>,
a reflection library that
causes performance problems when compiled to JavaScript.
Don't worry,
the Angular transformer converts the app's entry points
(<code>entry_points</code> in <code>pubspec.yaml</code>)
so that they don't use mirrors.
#dart_to_js_script_rewriter
h4 Using dart_to_js_script_rewriter
:marked
To improve the app's performance, convert the
HTML file to directly include the generated JavaScript;
one way to do that is with `dart_to_js_script_rewriter`.
To use the rewriter, specify `dart_to_js_script_rewriter` in both
the `dependencies` and `transformers` sections of the pubspec.
- var stylePattern = { otl: /(dart_to_js_script_rewriter.*$)|(- dart_to_js_script_rewriter.*$)|(dependencies:)|(transformers:)/gm };
+makeExample('quickstart/dart/pubspec.yaml', null, 'pubspec.yaml', stylePattern)
.alert.is-important
:marked
The `dart_to_js_script_rewriter` transformer must be
**after** the `angular2` transformer in `pubspec.yaml`.
:marked
For more information, see the docs for
[dart_to_js_script_rewriter](https://pub.dartlang.org/packages/dart_to_js_script_rewriter).
block server-watching
:marked
@ -160,7 +169,7 @@ block server-watching
.alert.is-important
:marked
Be sure to terminate the `pub serve` process once you stop working on this app.
Be sure to terminate your local server once you stop working on this app.
block project-file-structure
.filetree

View File

@ -1,7 +1,7 @@
block includes
include _util-fns
- var _Install = 'Install'
- var _prereq = 'Node.js'
- var _prereq = 'Node.js and npm'
- var _angular_browser_uri = '@angular/platform-browser-dynamic'
- var _angular_core_uri = '@angular/core'
- var _stepInit = 4 // Step # after NgModule step
@ -10,516 +10,289 @@ block includes
//- TS/Dart shared step counter
- var step = _stepInit
:marked
Our QuickStart goal is to build and run a super-simple
Angular application in #{_Lang}, and
establish a development environment for the remaining documentation samples
that also can be the foundation for real world applications.
.callout.is-helpful
header Don't want #{_Lang}?
p.
Although we're getting started in #{_Lang}, you can also write Angular apps
in #{_docsFor == 'ts' ? 'Dart' : 'TypeScript'} and JavaScript.
Just select either of those languages from the combo-box in the banner.
+ifDocsFor('ts')
aside.is-right
:marked
The live example link opens the finished application in
<a href="http://plnkr.co/" title="Plunker" target="_blank">Plunker</a> so that you can interact
with the code. You'll find live examples at the start of most sections.
:marked
# Try it!
Try the <live-example></live-example> which loads the sample app
<span if-docs="ts">
in <a href="http://plnkr.co/" title="Plunker" target="_blank">plunker</a>
</span>
and displays the simple message:
The QuickStart application has the structure of a real-world Angular application and
displays the simple message:
figure.image-display
img(src='/resources/images/devguide/quickstart/hello-angular.png' alt="Output of QuickStart app")
:marked
# Build this app!
**Try it out**. Here's a link to a <live-example></live-example>.
- [Prerequisite](#prereq): Install #{_prereq}
- [Step 1](#create-and-configure): Create the apps project folder and
define package dependencies and special project setup
- [Step 2](#root-component): Create the apps Angular root component
<li if-docs="ts">[Step 3](#ngmodule): Create an Angular Module</li>
- [Step !{step++}](#main): Add <span ngio-ex>main.ts</span>, identifying the root component to Angular
- [Step !{step++}](#index): Add `index.html`, the web page that hosts the application
- [Step !{step++}](#build-and-run): Build and run the app
- [Make some changes to the app](#make-some-changes)
- [Wrap up](#wrap-up)
+ifDocsFor('ts')
:marked
You can also <a href="!{_quickstartSrcURL}" target="_blank">
clone the entire QuickStart application</a> from GitHub.
h1 Build this application!
:marked
- [Prerequisite](#prereq): Install #{_prereq}.
- [Step 1](#create-and-configure): Create and configure the project.
- [Step 2](#ngmodule): Create your application.
<li if-docs="ts">[Step 3](#root-component): Create a component and add it to your application.</li>
- [Step !{step++}](#main): Start up your application.
- [Step !{step++}](#index): Define the web page that hosts the application.
- [Step !{step++}](#build-and-run): Build and run the application.
- [Step !{step++}](#make-changes): Make some live changes.
- [Wrap up and Next Steps](#wrap-up)
- var step = _stepInit // reinitialize step counter for headers to come
.l-main-section#prereq
h2 Prerequisite: #{_prereq}
h2 Prerequisite: Install #{_prereq}
block setup-tooling
:marked
Install **[Node.js® and npm](https://nodejs.org/en/download/)**
if they are not already on your machine.
.l-sub-section
:marked
**Verify that you are running at least node `v4.x.x` and npm `3.x.x`**
by running `node -v` and `npm -v` in a terminal/console window.
Older versions produce errors.
If Node.js and npm aren't already on your machine, <a href="http://blog.npmjs.org/post/85484771375/how-to-install-npm"
target="_blank">install them</a>. Our examples require node **v4.x.x** or higher and
npm **3.x.x** or higher. To check which version you are using, run `node -v` and `npm -v`
in a terminal window.
.l-main-section
.callout.is-helpful
header Download the source
:marked
Instead of following each step of these instructions, we can
[download the QuickStart source](!{_quickstartSrcURL})
from GitHub and follow its brief instructions.
h2#create-and-configure Step 1: Create and configure the project
.l-main-section
button(class="verbose off md-primary md-button md-ink-ripple", type="button", onclick="verbose(false)").
Hide explanations
button(class="verbose on md-primary md-button md-ink-ripple", type="button", onclick="verbose(true)").
View explanations
.l-verbose-section
:marked
*Explanations* describe the concepts and reasons behind the instructions.
Explanations have a thin border on the left like *this* block of text.
- var _package_and_config_files = _docsFor == 'dart' ? 'pubspec.yaml' : 'configuration files'
Click *Hide Explanations* to show only the instructions.
Click *View Explanations* to see everything again.
.l-sub-section
:marked
We'll see many code blocks as we build the QuickStart app. They're all easy to copy and paste:
code-example(format="nocode").
Click the glyph on the right to copy code snippets to the clipboard ==>
- var _package_and_config_files = _docsFor == 'dart' ? 'pubspec.yaml' : 'package definition and configuration files'
.l-main-section#create-and-configure
:marked
## Step 1: Create and configure the project
In this step you will:
* [Create the project folder](#create-the-project-folder)
* [Create #{_package_and_config_files}](#add-config-files)
* [#{_Install} packages](#install-packages)
In this step we:
* [(a) Create the project folder](#create-the-project-folder)
* [(b) Add #{_package_and_config_files}](#add-config-files)
* [(c) #{_Install} packages](#install-packages)
### (a) Create the project folder
h3 Create the project folder
:marked
Using a terminal window, create a directory for the project, and change into this
directory.
- var _ = _docsFor == 'dart' ? '_' : '-';
code-example(language="sh" class="code-shell").
mkdir angular2!{_}quickstart
cd angular2!{_}quickstart
mkdir angular!{_}quickstart
cd angular!{_}quickstart
h3#add-config-files (b) Add #{_package_and_config_files}
h3#add-config-files Create #{_package_and_config_files}
block package-and-config-files
- var _tsconfigUri = 'guide/typescript-configuration.html#tsconfig'
- var _typingsUri = 'guide/typescript-configuration.html#typings'
p Add the following package definition and configuration files to the project folder:
p Our typical Angular project needs several configuration files:
ul
li.
#[b package.json] lists packages the QuickStart app depends on and
defines some useful scripts.
See #[a(href="guide/npm-packages.html") Npm Package Configuration] for details.
#[b package.json] identifies npm package dependencies for the project.
li.
#[b tsconfig.json] is the TypeScript compiler configuration file.
See #[a(href="#{_tsconfigUri}") TypeScript Configuration] for details.
#[b tsconfig.json] defines how the TypeScript compiler generates JavaScript from the project's
files.
li.
#[b typings.json] identifies TypeScript definition files.
See #[a(href="#{_typingsUri}") TypeScript Configuration] for details.
li.
#[b systemjs.config.js], the SystemJS configuration file.
See discussion #[a(href="#systemjs") below].
#[b systemjs.config.js] provides information to a module loader about where to find
application modules, and registers all the necessary packages. It also
contains other packages that will be needed by later documentation examples.
p.
Create each of these files in your project directory. Populate them by pasting in text from
the tabs in the example box below.
a#config-files
+makeTabs(`
quickstart/ts/package.1.json,
quickstart/ts/tsconfig.1.json,
quickstart/ts/typings.1.json,
quickstart/ts/systemjs.config.1.js
`, '', `
package.json,
tsconfig.json,
typings.json,
systemjs.config.js
`)
h3#install-packages (c) #{_Install} packages
p.
Learn more about these configuration files in the
#[a(href="guide/npm-packages.html") Npm Package Configuration] guide and the
#[a(href="#{_tsconfigUri}") TypeScript Configuration] guide.
A detailed discussion of module loading is beyond the scope of this guide.
.callout.is-helpful
header SystemJS or Webpack?
p.
Although we use SystemJS for illustrative purposes here, it's only one option for loading
modules. Use the module loader that you prefer. For Webpack and Angular, see <a
href="guide/webpack.html" >
Webpack: an Introduction</a>. Or, learn more about SystemJS configuration in general <a href="https://github.com/systemjs/systemjs/blob/master/docs/config-api.md" target="_blank">here</a>.
h3#install-packages #{_Install} packages
block install-packages
:marked
We install the packages listed in `package.json` using `npm`. Enter the
following command in a terminal window (command window in Windows):
Using npm from the command line, install the packages listed in `package.json` with the command:
code-example(language="sh" class="code-shell").
npm install
.l-sub-section
:marked
The `typings` folder could not show up after `npm install`. If so, please install them manually.
:marked
Error messages&mdash;in red&mdash;might appear during the install, and you might see `npm WARN` messages. As long as there are no `npm ERR!` messages at the end, you can assume success.
code-example(language="sh" class="code-shell").
npm run typings install
:marked
You should now have the following structure:
.alert.is-important
:marked
Scary <span style="color:red; font-weight: bold">error messages in red</span> may appear **during** install.
The install typically recovers from these errors and finishes successfully.
.l-verbose-section(class="l-verbose-inherit")
:marked
#### npm errors and warnings
All is well if there are no console messages starting with `npm ERR!` *at the end* of **npm install**.
There might be a few `npm WARN` messages along the way &mdash; and that is perfectly fine.
We often see an `npm WARN` message after a series of `gyp ERR!` messages.
Ignore them. A package may try to recompile itself using `node-gyp`.
If the recompile fails, the package recovers (typically with a pre-built version)
and everything works.
Just make sure there are no `npm ERR!` messages at the end of `npm install`.
.l-verbose-section
:marked
#### Adding the libraries and packages we need with *npm*
Angular application developers rely on the _[npm](https://docs.npmjs.com)_
package manager to install the libraries and packages their apps require.
The Angular team recommends the starter-set of packages specified in the
`dependencies` and `devDependencies` sections.
See the [npm packages](guide/npm-packages.html) chapter for details.
#### Helpful scripts
We've included a number of npm scripts in our suggested `package.json` to handle common development tasks:
+makeJson('quickstart/ts/package.1.json',{ paths: 'scripts'}, 'package.json (scripts)')(format=".")
:marked
We execute most npm scripts in the following way: `npm run` followed by a *script-name*.
Some commands (such as `start`) don't require the `run` keyword.
Here's what these scripts do:
* `npm start` - runs the compiler and a server at the same time, both in "watch mode"
* `npm run tsc` - runs the TypeScript compiler once
* `npm run tsc:w` - runs the TypeScript compiler in watch mode;
the process keeps running, awaiting changes to TypeScript files and recompiling when it sees them
* `npm run lite` - runs the <a href="https://www.npmjs.com/package/lite-server" target="_blank">lite-server</a>,
a light-weight, static file server with excellent support for Angular apps that use routing
* `npm run typings` - runs the [*typings* tool](#{_typingsUri}) separately
* `npm run postinstall` - called by *npm* automatically *after* it successfully completes package installation.
This script installs the [TypeScript definition files](#{_typingsUri}) defined in `typings.json`
.filetree
.file angular-quickstart
.children
.file node_modules ...
.file package.json
.file systemjs.config.js
.file tsconfig.json
:marked
**We're all set.** Let's write some code.
You're now ready to write some code!
.l-main-section#root-component
.l-main-section
h2#ngmodule Step 2: Create your application
block create-your-app
:marked
You compose Angular applications into closely related blocks of functionality with
[NgModules](guide/ngmodule.html). Angular itself is split into separate Angular Modules. This
makes it possible for you to keep payload size small by only importing the parts of Angular
that your application needs.
Every Angular application has at least one module: the _root module_, named `AppModule` here.
:marked
## Step 2: Our first Angular component
Let's create a folder to hold our application and add a super-simple Angular component.
**Create #{_an} #{_appDir} subfolder** off the project root directory:
code-example.
code-example.code-shell.
mkdir #{_appDir}
a#app-component
p.
#[b Create the component file]
#[code #[+adjExPath('app/app.component.ts')]] (in this newly created directory) with the following content:
+ifDocsFor('ts')
:marked
Create the file `app/app.module.ts` with the following content:
+makeExample('app/app.module.1.ts')(format='.')
:marked
This is the entry point to your application.
Since the QuickStart application is a web application that runs in a browser, your root module
needs to import the
[`BrowserModule`](../latest/api/platform-browser/index/BrowserModule-class.html)
from `@angular/platform-browser` to the `imports` array.
This is the smallest amount of Angular that is needed for a minimal application to run in the
browser.
The QuickStart application doesn't do anything else, so you don't need any other modules. In a real
application, you'd likely import [`FormsModule`](../latest/api/forms/index/FormsModule-class.html)
as well as [`RouterModule`](../latest/api/router/index/RouterModule-class.html) and
[`HttpModule`](../latest/api/http/index/HttpModule-class.html). These are introduced in the
[Tour of Heroes Tutorial](./tutorial/).
.l-main-section
h2#root-component Step 3: Create a component and add it to your application
:marked
Every Angular application has at least one component: the _root component_, named `AppComponent`
here.
Components are the basic building blocks of Angular applications. A component controls a portion
of the screen&mdash;a *view*&mdash;through its associated template.
#app-component
:marked
**Create the component file** <span ngio-ex>app/app.component.ts</span> with the following content:
+makeExample('app/app.component.ts')
.l-verbose-section
:marked
### AppComponent is the root of the application
Every Angular app has at least one **root component**, conventionally named `AppComponent`,
that hosts the client user experience.
Components are the basic building blocks of Angular applications.
A component controls a portion of the screen &mdash; a *view* &mdash; through its associated template.
This QuickStart has only one, extremely simple component.
But it has the essential structure of every component we'll ever write:
* One or more [import](#component-import)
statements to reference the things we need.
* A [@Component #{_decorator}](#component-decorator)
that tells Angular what template to use and how to create the component.
* A [component class](#component-class)
that controls the appearance and behavior of a view through its template.
a#component-import
:marked
### Import
Angular apps are modular. They consist of many files each dedicated to a purpose.
Angular itself is modular. It is a collection of library modules
each made up of several, related features that we'll use to build our application.
When we need something from a module or library, we import it.
Here we import the Angular core so that our component code can have access to
the `@Component` #{_decorator}.
+makeExcerpt('app/app.component.ts', 'import')
h3#component-decorator @Component #{_decorator}
+ifDocsFor('ts')
:marked
`Component` is a *decorator function* that takes a *metadata object* as argument.
We apply this function to the component class by prefixing the function with the
**@** symbol and invoking it with a metadata object, just above the class.
:marked
`@Component` is #{_a} *#{_decorator}* that allows us to associate *metadata* with the
component class.
The metadata tells Angular how to create and use this component.
+makeExcerpt('app/app.component.ts', 'metadata')
block annotation-fields
:marked
This particular metadata object has two fields, a `selector` and a `template`.
:marked
The **selector** specifies a simple CSS selector for an HTML element that represents the component.
>The element for this component is named `my-app`.
Angular creates and displays an instance of our `AppComponent`
wherever it encounters a `my-app` element in the host HTML.
The **template** specifies the component's companion template,
written in an enhanced form of HTML that tells Angular how to render this component's view.
>Our template is a single line of HTML announcing "Hello Angular!".
>A more advanced template could contain data bindings to component properties
and might identify other application components which have their own templates.
These templates might identify yet other components.
In this way an Angular application becomes a tree of components.
:marked
### Component class
At the bottom of the file is an empty, do-nothing class named `AppComponent`.
+makeExcerpt('app/app.component.ts', 'class')
:marked
When we're ready to build a substantive application,
we can expand this class with properties and application logic.
Our `AppComponent` class is empty because we don't need it to do anything in this QuickStart.
+ifDocsFor('ts')
:marked
We **export** `AppComponent` so that we can **import** it elsewhere in our application,
as we'll see when we create `app.module.ts`.
- var _decorator_function = _docsFor == 'dart' ? 'annotation' : 'decorator function';
:marked
The QuickStart application has the same essential structure as any other Angular component:
* **An import statement**. Importing gives your component access to
Angular's core [`@Component` !{_decorator_function}](./api/core/index/Component-decorator.html).
* **A @Component #{_decorator}** that associates *metadata* with the
`AppComponent` component class:
- a *selector* that specifies a simple CSS selector for an HTML element that represents
the component.
- a *template* that tells Angular how to render the component's view.
* **A component class** that controls the appearance and behavior of a view
through its template. Here, you only have the root component, `AppComponent`. Since you don't
need any application logic in the simple QuickStart example, it's empty.
+ifDocsFor('ts')
.l-main-section#ngmodule
:marked
## Step 3: Our own `app.module.ts`
You *export* the `AppComponent` class so that you can *import* it into the application that you
just created.
We compose Angular apps into closely related blocks of functionality with [Angular Modules](guide/ngmodule.html).
Every app requires at least one module, the _root module_, that we call `AppModule` by convention.
Edit the file `app/app.module.ts` to import your new `AppComponent` and add it in the
declarations and bootstrap fields in the `NgModule` decorator:
Create the file `app/app.module.ts` with the following content:
+makeExample('app/app.module.ts')(format='.')
.l-verbose-section
:marked
We're passing metadata to the `NgModule` decorator function:
1. `imports` - the _other_ modules that export material we need in _this_ module.
Almost every application's _root module_ should import the `BrowserModule`.
1. `declarations` - components and directives that belong to _this_ module.
1. `bootstrap` - identifies the _root component_ that Angular should _bootstrap_ when it starts the application.
We import our lone `app.component.ts` and add it to both the `declarations` and `bootstrap` arrays.
### Angular Modules import other modules
Notice that we also add the `BrowserModule` from `@angular/platform-browser` to the `imports` array.
This is the Angular Module that contains all the needed Angular bits and pieces to run our app in the browser.
Angular itself is split into separate Angular Modules so we only need to import the ones we really use.
One of the most common ones is `FormsModule`, and soon we'll also see `RouterModule` and `HttpModule`.
+makeExample('app/app.module.ts')
.l-main-section
h2#main Step !{step++}: Add #[code #[+adjExPath('main.ts')]]
h2#main Step !{step++}: Start up your application
block create-main
:marked
Now we need something to tell Angular to load the app module.
Now you need to tell Angular to start up your application.
Create the file `app/main.ts` with the following content:
+makeExample('app/main.ts')
- var _pBD_bootstrapModule = _docsFor == 'dart' ? _bootstrapModule : 'platformBrowserDynamic().bootstrapModule'
.l-verbose-section
:marked
This code initializes the platform that your application runs in, then uses the platform to
bootstrap your `!{_AppModuleVsAppComp}`.
### Why create separate *<span ngio-ex>main.ts</span>*<span if-docs="ts">, app module</span> and app component files?
App bootstrapping is a separate concern from<span if-docs="ts"> creating a module or</span>
presenting a view. Testing the component is much easier if it doesn't also try to run the entire application.
.callout.is-helpful
header Bootstrapping is platform-specific
:marked
We import the two things we need to launch the application:
1. Angular's browser `!{_platformBrowserDynamicVsBootStrap}` function
1. The application !{_moduleVsRootComp}, `!{_AppModuleVsAppComp}`.
Then we call `!{_pBD_bootstrapModule}` with `!{_AppModuleVsAppComp}`.
### Bootstrapping is platform-specific
Notice that we import the `!{_platformBrowserDynamicVsBootStrap}` function
from `#{_angular_browser_uri}`, not `#{_angular_core_uri}`.
Bootstrapping isn't core because there isn't a single way to bootstrap the app.
True, most applications that run in a browser call the bootstrap function from
this library.
But it is possible to load a !{_moduleVsComp} in a different environment.
We might load it on a mobile device with [Apache Cordova](https://cordova.apache.org/) or [NativeScript](https://www.nativescript.org/).
We might wish to render the first page of our application on the server
to improve launch performance or facilitate
[SEO](http://www.google.com/webmasters/docs/search-engine-optimization-starter-guide.pdf).
These targets require a different kind of bootstrap function that we'd import from a different library.
### Why create separate *<span ngio-ex>main.ts</span>*<span if-docs="ts">, app module</span> and app component files?
Then <span ngio-ex>main.ts</span><span if-docs="ts">, app module</span>
and the app component files are tiny.
This is just a QuickStart.
We could have merged these files into one and spared ourselves some complexity.
We'd rather demonstrate the proper way to structure an Angular application.
App bootstrapping is a separate concern from<span if-docs="ts"> creating a module or</span>
presenting a view.
Mixing concerns creates difficulties down the road.
We might launch the `!{_AppModuleVsAppComp}` in multiple environments with different bootstrappers.
Testing the component is much easier if it doesn't also try to run the entire application.
Let's make the small extra effort to do it *the right way*.
Because the QuickStart application runs directly in the browser, `main.ts` imports the
`!{_platformBrowserDynamicVsBootStrap}` function from `#{_angular_browser_uri}`, not
`#{_angular_core_uri}`. On a mobile device, you might load a !{_moduleVsComp} with
[Apache Cordova](https://cordova.apache.org/) or
[NativeScript](https://www.nativescript.org/), using a bootstrap function that's specific
to that platform.
.l-main-section
h2#index Step !{step++}: Add #[code index.html]
h2#index Step !{step++}: Define the web page that hosts the application
:marked
In the *#{_indexHtmlDir}* folder
In the *#{_indexHtmlDir}* folder,
create an `index.html` file and paste the following lines into it:
+makeExample('index.html')
.l-verbose-section
block commentary-on-index-html
:marked
The `index.html` file defines the web page that hosts the application.
The noteworthy sections here are:
+ifDocsFor('ts')
:marked
The noteworthy sections of HTML are:
* JavaScript libraries: `core-js` polyfills for older browsers, the `zone.js` and
`reflect-metadata` libraries needed by Angular, and the `SystemJS` library for module loading.
* Configuration file for `SystemJS`, and a script
where you import and run the `app` module which refers to the `main` file that you just
wrote.
* The `<my-app>` tag in the `<body>` which is *where your app lives!*
1. The JavaScript [libraries](#libraries)
2. Configuration file for [SystemJS](#systemjs), and a script
where we import and run the `app` module which refers to the `main` file that we just wrote.
3. The [`<my-app>`](#my-app) tag in the `<body>` which is *where our app lives!*
:marked
### Libraries
We loaded the following scripts
+makeExcerpt('index.html', 'libraries')
:marked
We begin with `core-js`'s ES2015/ES6 shim which monkey patches the global context (window) with essential features of ES2015 (ES6).
Next are the polyfills for Angular2, `zone.js` and `reflect-metadata`.
Then the [SystemJS](#systemjs) library for module loading.
We'll make different choices as we gain experience and
become more concerned about production qualities such as
load times and memory footprint.
h3#systemjs SystemJS
:marked
QuickStart uses <a href="https://github.com/systemjs/systemjs" target="_blank">SystemJS</a>
to load application and library modules. [Earlier](#add-config-files) we
added the `systemjs.config.js` file to the project root.
There are alternatives that work just fine including the well-regarded
[webpack](guide/webpack.html).
SystemJS happens to be a good choice.
But we want to be clear that it was a *choice* and not a *preference*.
All module loaders require configuration and all loader configuration
becomes complicated rather quickly as soon as the file structure diversifies and
we start thinking about building for production and performance.
We suggest becoming well-versed in the loader of your choice.
Learn more about SystemJS configuration
<a href="https://github.com/systemjs/systemjs/blob/master/docs/config-api.md" target="_blank">here</a>.
With those cautions in mind, what are we doing in the
QuickStart [`systemjs.config.js` configuration file we added earlier](#config-files)?
First, we create a map to tell SystemJS where to look when we import some module.
Then, we register all our packages to SystemJS:
all the project dependencies and our application package, `app`.
.l-sub-section
:marked
Our QuickStart doesn't use all of the listed packages
but any substantial application will want many of them
and all of the listed packages are required by at least one of the documentation samples.
There is no runtime harm in listing packages that we don't need as they will only be loaded when requested.
:marked
The `app` package tells SystemJS what to do when it sees a request for a
module from the `app/` folder.
Our QuickStart makes such requests when one of its
application TypeScript files has an import statement like this:
+makeExcerpt('app/main.ts', 'import')
:marked
Notice that the module name (after `from`) does not mention a filename extension.
In the configuration we tell SystemJS to default the extension to `js`, a JavaScript file.
That makes sense because we transpile TypeScript to JavaScript
*before* running the application.
.l-sub-section
:marked
#### Transpiling in the browser
In the live example on plunker we transpile (AKA compile) to JavaScript in the browser
on the fly. _That's fine for a demo_.
**Do not transpile in the browser during development or for production**.
We strongly recommend transpiling (AKA compiling) to JavaScript during a build phase
before running the application for several reasons including:
* We see compiler warnings and errors that are hidden from us in the browser.
* Precompilation simplifies the module loading process and
it's much easier to diagnose problems when this is a separate, external step.
* Precompilation means a faster user experience because the browser doesn't waste time compiling.
* We iterate development faster because we only recompile changed files.
We notice the difference as soon as the app grows beyond a handful of files.
* Precompilation fits into a continuous integration process of build, test, deploy.
:marked
The `System.import` call tells SystemJS to import the `main` file
(`main.js` ... after transpiling `main.ts`, remember?);
`main` is where we tell Angular to launch the application.
We also catch and log launch errors to the console.
All other modules are loaded upon request
either by an import statement or by Angular itself.
### *&lt;my-app&gt;*
a#my-app
:marked
When Angular calls the `!{_bootstrapModule}` function in <span ngio-ex>main.ts</span>,
it reads the `!{_AppModuleVsAppComp}` metadata<span if-docs="ts">, sees that
`AppComponent` is the bootstrap component</span>,
finds the `my-app` selector, locates an element tag named `my-app`,
and renders our application's view between those tags.
:marked
### Add some style
Styles aren't essential but they're nice, and `index.html` assumes we have
Styles aren't essential, but they're nice, and `index.html` assumes that you have
a stylesheet called `styles.css`.
Create a `styles.css` file in the *#{_indexHtmlDir}* folder and start styling,
Create a `styles.css` file in the *#{_indexHtmlDir}* folder, and start styling,
perhaps with the minimal styles shown below.
+makeExcerpt('styles.css (excerpt)', 'quickstart')
@ -527,53 +300,54 @@ h2#index Step !{step++}: Add #[code index.html]
.callout.is-helpful
:marked
For the full set of master styles used by the documentation samples,
see [styles.css](https://github.com/angular/angular.io/blob/master/public/docs/_examples/styles.css).
see [styles.css](https://github.com/angular/angular.io/blob/master/public/docs/_examples/_boilerplate/styles.css).
.l-main-section#build-and-run
h2 Step !{step++}: Build and run the app!
h2 Step !{step++}: Build and run the application
block run-app
:marked
Open a terminal window and enter this command:
code-example.
code-example.code-shell.
npm start
:marked
That command runs two parallel node processes
1. The TypeScript compiler in watch mode
1. A static server called **lite-server** that loads `index.html` in a browser
and refreshes the browser when application files change
aside.is-right
:marked
[Read more](https://github.com/angular/quickstart/blob/master/README.md#npm-scripts) about
other useful npm scripts included in this example's `package.json`.
In a few moments, a browser tab should open and display
:marked
That command runs the following two parallel node processes:
* The TypeScript compiler in watch mode.
* A static file server called _lite-server_ that loads `index.html` in a browser
and refreshes the browser when application files change.
In a few moments, a browser tab should open and display the following:
figure.image-display
img(src='/resources/images/devguide/quickstart/hello-angular.png' alt="Output of QuickStart app")
:marked
**Great job!**
block build-app
//- Nothing for ts.
.l-main-section#make-changes
h2 Step !{step++}: Make some live changes
:marked
## Make some changes
Try changing the message in <span ngio-ex>app/app.component.ts</span> to "Hello Again Angular!".
Try changing the message to "Hello Again Angular!".
block server-watching
:marked
The TypeScript compiler and `lite-server` are watching.
They should detect the change, recompile the TypeScript into JavaScript,
refresh the browser, and display the revised message.
It's a nifty way to develop an application!
The TypeScript compiler and `lite-server` will detect your change, recompile the TypeScript into JavaScript,
refresh the browser, and display your revised message.
We close the terminal window when we're done to terminate both the compiler and the server.
Close the terminal window when you're done to terminate both the compiler and the server.
.l-main-section
h2#wrap-up Wrap up and next steps
:marked
# Wrap up
Our final project folder structure looks like this:
The final project folder structure looks like this:
block project-file-structure
.filetree
.file angular2-quickstart
.file angular-quickstart
.children
.file app
.children
@ -587,46 +361,22 @@ block project-file-structure
.file systemjs.config.js
.file tsconfig.json
:marked
Here are the file contents:
block project-files
+makeTabs(`
quickstart/ts/app/app.component.ts,
quickstart/ts/app/app.module.ts,
quickstart/ts/app/main.ts,
quickstart/ts/index.html,
quickstart/ts/package.1.json,
quickstart/ts/tsconfig.1.json,
quickstart/ts/styles.css,
quickstart/ts/systemjs.config.1.js`
,
',,,,,,, quickstart,',
`app/app.component.ts,
app/app.module.ts,
app/main.ts,
index.html,
package.json,
tsconfig.json,
styles.css (excerpt),
systemjs.config.js`)
To see the file contents, open the <live-example></live-example>.
.l-main-section
:marked
## What next?
Our first application doesn't do much. It's basically "Hello, World" for Angular.
This first application doesn't do much. It's basically "Hello, World" for Angular.
We kept it simple in our first pass: we wrote a little Angular component,
created a simple `index.html`, and launched with a
static file server. That's about all we'd expect to do for a "Hello, World" app.
You wrote a little Angular component, created a simple `index.html`, and launched with a
static file server.
**We have greater ambitions!**
+ifDocsFor('ts')
:marked
The good news is that the overhead of setup is (mostly) behind us.
We'll probably only touch the `package.json` to update libraries.
We'll likely open `index.html` only if we need to add a library or some css stylesheets.
You also created the basic application setup that you'll re-use for other
sections in this guide. From here, the changes you'll make in the
`package.json` or `index.html` files are only minor updates to add libraries or some css
stylesheets. You also won't need to revisit module loading again.
:marked
We're about to take the next step and build a small application that
demonstrates the great things we can build with Angular.
Join us on the [Tour of Heroes Tutorial](./tutorial)!
To take the next step and build a small application that demonstrates real features that you can
build with Angular, carry on to the [Tour of Heroes tutorial](./tutorial)!

View File

@ -4,26 +4,18 @@ block includes
- var _prereq = 'Node.js and npm'
- var _angular_browser_uri = '@angular/platform-browser-dynamic'
- var _angular_core_uri = '@angular/core'
- var _stepInit = 3 // Step # after NgModule step
- var _stepInit = 4 // Step # after NgModule step
- var _quickstartSrcURL='https://github.com/angular/quickstart/blob/master/README.md'
//- TS/Dart shared step counter
- var step = _stepInit
.callout.is-helpful
header Don't want #{_Lang}?
p.
Although you're getting started in #{_Lang}, you can also write Angular applications
in JavaScript and #{_docsFor == 'ts' ? 'Dart' : 'TypeScript'}. Use the language selector in the
left nav to switch development languages for this guide.
.l-main-section
h1 Overview
aside.is-right
:marked
The live example link opens the finished application in
<a href="http://plnkr.co/" title="Plunker" target="_blank">Plunker</a> so that you can interact
with the code. You'll find live examples at the start of most sections.
+ifDocsFor('ts')
aside.is-right
:marked
The live example link opens the finished application in
<a href="http://plnkr.co/" title="Plunker" target="_blank">Plunker</a> so that you can interact
with the code. You'll find live examples at the start of most sections.
:marked
The QuickStart application has the structure of a real-world Angular application and
@ -35,16 +27,18 @@ figure.image-display
:marked
**Try it out**. Here's a link to a <live-example></live-example>.
You can also <a href="https://github.com/angular/quickstart/blob/master/README.md" target="_blank">
clone the entire QuickStart application</a> from GitHub.
+ifDocsFor('ts')
:marked
You can also <a href="!{_quickstartSrcURL}" target="_blank">
clone the entire QuickStart application</a> from GitHub.
h2 Build this application!
h1 Build this application!
:marked
- [Prerequisite](#prereq): Install #{_prereq}.
- [Step 1](#create-and-configure): Create and configure the project.
<span if-docs="ts"><li>[Step 2](#ngmodule): Create your application.</span>
- [Step !{step++}](#root-component): Create a component and add it to your application.
- [Step 2](#ngmodule): Create your application.
<li if-docs="ts">[Step 3](#root-component): Create a component and add it to your application.</li>
- [Step !{step++}](#main): Start up your application.
- [Step !{step++}](#index): Define the web page that hosts the application.
- [Step !{step++}](#build-and-run): Build and run the application.
@ -54,7 +48,7 @@ h2 Build this application!
- var step = _stepInit // reinitialize step counter for headers to come
.l-main-section#prereq
h1 Prerequisite: Install #{_prereq}
h2 Prerequisite: Install #{_prereq}
block setup-tooling
:marked
@ -64,7 +58,7 @@ block setup-tooling
in a terminal window.
.l-main-section
h1#create-and-configure Step 1: Create and configure the project
h2#create-and-configure Step 1: Create and configure the project
- var _package_and_config_files = _docsFor == 'dart' ? 'pubspec.yaml' : 'configuration files'
@ -74,7 +68,7 @@ h1#create-and-configure Step 1: Create and configure the project
* [Create #{_package_and_config_files}](#add-config-files)
* [#{_Install} packages](#install-packages)
h2 Create the project folder
h3 Create the project folder
:marked
Using a terminal window, create a directory for the project, and change into this
directory.
@ -84,7 +78,7 @@ code-example(language="sh" class="code-shell").
mkdir angular!{_}quickstart
cd angular!{_}quickstart
h2#add-config-files Create #{_package_and_config_files}
h3#add-config-files Create #{_package_and_config_files}
block package-and-config-files
- var _tsconfigUri = 'guide/typescript-configuration.html#tsconfig'
@ -130,7 +124,7 @@ block package-and-config-files
Webpack: an Introduction</a>. Or, learn more about SystemJS configuration in general <a href="https://github.com/systemjs/systemjs/blob/master/docs/config-api.md" target="_blank">here</a>.
h2#install-packages #{_Install} packages
h3#install-packages #{_Install} packages
block install-packages
:marked
Using npm from the command line, install the packages listed in `package.json` with the command:
@ -154,9 +148,11 @@ block install-packages
:marked
You're now ready to write some code!
+ifDocsFor('ts')
.l-main-section
h1#ngmodule Step 2: Create your application
.l-main-section
h2#ngmodule Step 2: Create your application
block create-your-app
:marked
You compose Angular applications into closely related blocks of functionality with
[NgModules](guide/ngmodule.html). Angular itself is split into separate Angular Modules. This
@ -164,12 +160,13 @@ block install-packages
that your application needs.
Every Angular application has at least one module: the _root module_, named `AppModule` here.
:marked
**Create #{_an} #{_appDir} subfolder** off the project root directory:
**Create #{_an} #{_appDir} subfolder** off the project root directory:
code-example.code-shell.
mkdir #{_appDir}
code-example.code-shell.
mkdir #{_appDir}
+ifDocsFor('ts')
:marked
Create the file `app/app.module.ts` with the following content:
@ -192,8 +189,9 @@ block install-packages
[`HttpModule`](../latest/api/http/index/HttpModule-class.html). These are introduced in the
[Tour of Heroes Tutorial](./tutorial/).
.l-main-section
h1#root-component Step !{step++}: Create a component and add it to your application
.l-main-section
h2#root-component Step 3: Create a component and add it to your application
:marked
Every Angular application has at least one component: the _root component_, named `AppComponent`
here.
@ -201,38 +199,39 @@ h1#root-component Step !{step++}: Create a component and add it to your applicat
Components are the basic building blocks of Angular applications. A component controls a portion
of the screen&mdash;a *view*&mdash;through its associated template.
a#app-component
p.
#[b Create the component file]
#[code #[+adjExPath('app/app.component.ts')]] with the following content:
#app-component
:marked
**Create the component file** <span ngio-ex>app/app.component.ts</span> with the following content:
+makeExample('app/app.component.ts')
- var _decorator_function = _docsFor == 'dart' ? 'annotation' : 'decorator function';
:marked
The QuickStart application has the same essential structure as any other Angular component:
* **An import statement**. Importing gives your component access to
Angular's core [`@Component` decorator function](../latest/api/core/index/Component-decorator.html).
Angular's core [`@Component` !{_decorator_function}](./api/core/index/Component-decorator.html).
* **A @Component #{_decorator}** that associates *metadata* with the
`AppComponent` component class:
- a *selector* that specifies a simple CSS selector for an HTML element that represents
the component.
- a *template* that tells Angular how to render the component's view.
- a *selector* that specifies a simple CSS selector for an HTML element that represents
the component.
- a *template* that tells Angular how to render the component's view.
* **A component class** that controls the appearance and behavior of a view
through its template. Here, you only have the root component, `AppComponent`. Since you don't
need any application logic in the simple QuickStart example, it's empty.
+ifDocsFor('ts')
:marked
You *export* the `AppComponent` class so that you can *import* it into the application that you
just created.
You *export* the `AppComponent` class so that you can *import* it into the application that you
just created.
Edit the file `app/app.module.ts` to import your new `AppComponent` and add it in the
declarations and bootstrap fields in the `NgModule` decorator:
Edit the file `app/app.module.ts` to import your new `AppComponent` and add it in the
declarations and bootstrap fields in the `NgModule` decorator:
+makeExample('app/app.module.ts', null, title='app/app.module.ts')
+makeExample('app/app.module.ts')
.l-main-section
h1#main Step !{step++}: Start up your application
h2#main Step !{step++}: Start up your application
block create-main
:marked
@ -267,7 +266,7 @@ block create-main
to that platform.
.l-main-section
h1#index Step !{step++}: Define the web page that hosts the application
h2#index Step !{step++}: Define the web page that hosts the application
:marked
In the *#{_indexHtmlDir}* folder,
create an `index.html` file and paste the following lines into it:
@ -275,20 +274,21 @@ h1#index Step !{step++}: Define the web page that hosts the application
+makeExample('index.html')
+ifDocsFor('ts')
:marked
The noteworthy sections here are:
block commentary-on-index-html
:marked
The noteworthy sections here are:
* JavaScript libraries: `core-js` polyfills for older browsers, the `zone.js` and
`reflect-metadata` libraries needed by Angular, and the `SystemJS` library for module loading.
* Configuration file for `SystemJS`, and a script
where you import and run the `app` module which refers to the `main` file that you just
wrote.
* The [`<my-app>`](#my-app) tag in the `<body>` which is *where your app lives!*
* JavaScript libraries: `core-js` polyfills for older browsers, the `zone.js` and
`reflect-metadata` libraries needed by Angular, and the `SystemJS` library for module loading.
* Configuration file for `SystemJS`, and a script
where you import and run the `app` module which refers to the `main` file that you just
wrote.
* The `<my-app>` tag in the `<body>` which is *where your app lives!*
:marked
## Add some style
### Add some style
Styles aren't essential, but they're nice, and `index.html` assumes that you have
a stylesheet called `styles.css`.
@ -303,24 +303,24 @@ h1#index Step !{step++}: Define the web page that hosts the application
see [styles.css](https://github.com/angular/angular.io/blob/master/public/docs/_examples/_boilerplate/styles.css).
.l-main-section#build-and-run
h1 Step !{step++}: Build and run the application
h2 Step !{step++}: Build and run the application
block run-app
:marked
Open a terminal window and enter this command:
code-example.code-shell.
npm start
aside.is-right
aside.is-right
:marked
[Read more](https://github.com/angular/quickstart/blob/master/README.md#npm-scripts) about
other useful npm scripts included in this example's `package.json`.
:marked
[Read more](https://github.com/angular/quickstart/blob/master/README.md#npm-scripts) about
other useful npm scripts included in this example's `package.json`.
That command runs the following two parallel node processes:
* The TypeScript compiler in watch mode.
* A static file server called _lite-server_ that loads `index.html` in a browser
and refreshes the browser when application files change.
:marked
That command runs the following two parallel node processes:
* The TypeScript compiler in watch mode.
* A static file server called _lite-server_ that loads `index.html` in a browser
and refreshes the browser when application files change.
In a few moments, a browser tab should open and display the following:
In a few moments, a browser tab should open and display the following:
figure.image-display
img(src='/resources/images/devguide/quickstart/hello-angular.png' alt="Output of QuickStart app")
@ -330,19 +330,19 @@ block build-app
//- Nothing for ts.
.l-main-section#make-changes
h1 Step !{step++}: Make some live changes
h2 Step !{step++}: Make some live changes
:marked
Try changing the message in `app/app.component.ts` to "Hello Again Angular!".
Try changing the message in <span ngio-ex>app/app.component.ts</span> to "Hello Again Angular!".
block server-watching
:marked
The TypeScript compiler and `lite-server` will detect your change, recompile the TypeScript into JavaScript,
refresh the browser, and display your revised message.
Close the terminal window when you're done to terminate both the compiler and the server.
.l-main-section
h1#wrap-up Wrap up and next steps
h2#wrap-up Wrap up and next steps
:marked
The final project folder structure looks like this:
block project-file-structure