Let's start from zero and build a super simple Angular 2 application in TypeScript.
让我们从零开始使用 TypeScript 构建一个超级简单的 Angular 2 应用.
Although we're getting started in TypeScript, you can also write Angular 2 apps in JavaScript and Dart by selecting either of those languages from the combo-box in the banner.
尽管我们正在使用 TypeScript, 你也可以使用 JavaScript 和 Dart 开发你的 Angular 2 的应用, 请选择上方复选框中的其他语言.
See It Run! 看看它是怎么运行的!
Running the live example is the quickest way to see an Angular 2 app come to life.
运行 实时案例 最快的方式查看 Angular 2 应用.
Clicking that link fires up a browser, loads the sample in plunker, and displays a simple message:
点击链接打开浏览器, 在plunker中加载案例并且显示简单的信息.

Here is the file structure:
这里是文件目录结构:
Functionally, it's an index.html and two TypeScript files in an app/ folder.
We can handle that!
功能上来讲, 在 app/ 目录下有一个 index.html 文件和两个 TypeScript 文件. 我们可以操作他们.
Of course we won't build many apps that only run in plunker. Let's follow a process that's closer to what we'd do in real life.
确实我们不能在 plunker 上构建很多应用. 所以让我们使用以下步骤开始我们实际开发部署吧.
- Set up our development environment
- Write the Angular root component for our app
- Bootstrap it to take control of the main web page
Write the main page (
index.html)配置我们的开发环境
- 为我们的应用开发 Angular 根组件 (root component)
- 使用 Bootstrap 来控制我们主页面
- 开发主页面 (
index.html)
We really can build the QuickStart from scratch in five minutes if we follow the instructions and ignore the commentary.
如果我们依照指导并且忽略注释, 我们真的能够在5分钟内构建一个QuickStart应用.
Most of us will be interested in the "why" as well as the "how" and that will take longer.
更多的人除了 "如何做"以外, 还会对 "为什么" 感兴趣. 那将会花费更多的时间来理解.
Development Environment 开发环境
We'll need a place to stand (the application project folder), some libraries, some TypeScript configuration and the TypeScript-aware editor of your choice.
我们需要一下工具及资源: 一个存放应用项目的文件夹, 一些库, 一些 TypeScript 的配置, 以及选择一个能够识别TypeScript的编辑器.
Create a new project folder 创建一个新的项目文件
Add the libraries we need 添加需要的库
We recommend the npm package manager for acquiring and managing our development libraries.
我们推荐使用 npm 包管理器获取和管理我们的开发库.
Don't have npm? Get it now because we're going to use it now and repeatedly throughout this documentation.
还没有使用 npm? 马上获取 由于我们将会在本文档中频繁的使用 npm.
Add a package.json file to the project folder and copy/paste the following:
添加一个文件 package.json 到项目目录, 并且复制粘贴一下代码到文件中.
Itching to know the details? We explain in the appendix below
急于想知道细节吗? 我们将会在下面的附录中解释 appendix below.
Install these packages. Open a terminal window (command window in Windows) and run this npm command.
安装这些包. 打开终端窗口 (Windows环境打开 CMD 窗口)并且执行一下 npm 指令.
Scary error messages in red may appear during install. Ignore them. The install will succeed. See the appendix below for more information.
在安装过程中令人紧张的错误信息 error messages in red. 忽略他们, 该安装将会成功. 查看下面的附录获取更多信息. appendix below
Configure TypeScript 配置 TypeScript
We must guide the TypeScript compiler with very specific settings.
我们必须使用非常特殊的配置来指导 TypeScript 编译器.
Add a tsconfig.json file to the project folder and copy/paste the following:
添加文件 tsconfig.json 到项目文件夹, 且复制粘贴一下代码到文件中.
We explore the tsconfig.json in an appendix below
我们会在附录中探索文件 tsconfig.json. appendix below
We're all set. Let's write some code.
配置全部完成了! 让我们开始编写代码吧,
Our First Angular Component 我们第一个 Angular 组件
The Component is the most fundamental of Angular concepts. A component manages a view - a piece of the web page where we display information to the user and respond to user feedback.
Component组件是Angular最为基础的概念. 一个组件管理一个视图(view) - 也就是向用户展示信息和响应用户反馈的页面.
Technically, a component is a class that controls a view template. We'll write a lot of them as we build Angular apps. This is our first attempt so we'll keep it ridiculously simple.
技术角度, 一个组件是一个控制视图模板的类. 在我们构建Angular应用的时候, 将会编写很多组件. 由于这是我们第一个尝试开发, 所以我们让该组件保持简洁.
Create an application source sub-folder 创建应用源码的子文件夹
We like to keep our application code in a sub-folder off the root called app/.
Execute the following command in the console window.
我们更倾向于将我们的应用代码放到子文件夹中而非根文件夹 app/.
在控制台窗口执行一下命令(linux/mac/Mingw in Windows)
Add the component file 添加组件文件
Now add a file named app.component.ts and paste the following lines:
现在我们增加一个文件 app.component.ts 并且复制粘贴一下代码:
Let's review this file in detail, starting at the bottom where we define a class.
让我们回顾一下该文件的细节, 代码底部我们定义了一个类 (class).
The Component class 组件类
At the bottom of the file is an empty, do-nothing class named AppComponent.
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.
文件的底部是一个空的不做任何事情的类, 命名为 AppComponent.
当我们准备开始构建实质性的应用时,
我们可以使用属性和应用逻辑来扩展这个类.
我们的 AppComponent 类现在是空的因为在该案例中我们不需要它做任何事.
Modules 模块
Angular apps are modular. They consist of many files each dedicated to a purpose.
Angular 应用是模块化的. 他们包含无数的文件, 每个文件专注于一个目标.
Most application files export one thing such as a component.
Our app.component file exports the AppComponent.
大多数应用文件导出至一件事情,例如组件(component).
我们的 app.component 文件导出至 AppComponent.
The act of exporting turns the file into a module. The name of the file (without extension) is usually the name of the module. Accordingly, 'app.component' is the name of our first module.
导出的动作将文件变为模块. 文件名(不包括扩展名)通常是模块名. 因此, 'app.component' 是我们第一个模块的名字.
A more sophisticated application would have child components that descended from
AppComponent in a visual tree.
A more sophisticated app would have more files and modules, at least as many as it had components.
更加复杂的应用一般会有子组件继承自 AppComponent, 呈树状机构.
更加负责的应用一般会有更多的文件和模块, 至少和组件数量匹配.
This Quickstart isn't sophisticated; one component is all we need. Yet modules play a fundamental organizational role in even this small app.
该Quickstart案例并不复杂; 我们只需要一个组件. 然而即使在这个非常小的应用中, 模块也起到了基础组织的作用.
Modules rely on other modules. In TypeScript Angular apps, when we need something
provided by another module, we import it.
When another module needs to refer to AppComponent, it imports the AppComponent symbol like this:
模块依赖于其他模块. 在 TypeScript Angular 应用, 当我们需要一些其他模块的功能时,
我们需要引入这个模块.
当一个其他的模块需要引用到 AppComponent, 它应该引入 AppComponent 其标识应该像这样:
Angular is also modular. It is a collection of library modules. Each library is itself a module made up of several, related feature modules.
Angular 也是模块化的. 它是一个模块库的合集. 每个库都是有若干相关特性的模块组合成的一个模块.
When we need something from Angular, we import it from an Angular library module. We need something from Angular right now to help us define metadata about our component.
当我们需要 Angular 的一些东西时, 我们可以从 Angular 的模块库中引入该模块. 我们现在需要一些 Angular 的内容来帮助我们定义我们组件的元数据(metadata).
Component Metadata 组件元数据
A class becomes an Angular component when we give it metadata. Angular needs the metadata to understand how to construct the view and how the component interacts with other parts of the application.
当我们给一个类添加元数据后, 该类就会变成 Angular 的组件. Angular 需要元数据来理解如何构建视图以及组件如何和应用其他部分进行交互.
We define a component's metadata with the Angular Component function.
We access that function by importing it from the primary Angular library,angular2/core.
我们定义一个组件的元数据为 Angular的组件函数 Componet.
In TypeScript we apply that function to the class as a decorator by prefixing it with the @ symbol and invoking it just above the component class:
在TypeScript中, 我们应用该函数与类作为装饰器通过使用前缀 @ 符号 并且在组件类上面调用它:
@Component tells Angular that this class is an Angular component.
The configuration object passed to the @Component method has two
fields, a selector and a template.
@Component 告诉 Angular, 这个类是一个Angular组件.
传到 @Component 方法的对象的配置有两个域, 一个是 selector, 另一个是 template.
The selector specifies a simple CSS selector for a host HTML element named my-app.
Angular creates and displays an instance of our AppComponent
wherever it encounters a my-app element in the host HTML.
selector``为名字为my-app的 HTML元素, 指定了简单的 CSS 选择器.
当它在服务器HTML文件中遇到my-app元素时, Angular 创建并展示一个AppComponet` 的实例.
Remember the my-app selector! We'll need that information when we write our index.html
记住这个 my-app 选择器! 当我们编写 index.html 时, 将需要该信息.
The template property holds the component's companion template.
A template is a form of HTML that tells Angular how to render a view.
Our template is a single line of HTML announcing "My First Angular App".
template 属性包含了组件相对应的模板.
一个模板是一个能够告诉 Angular 如何渲染一个对象的 HTML 表单.
我们的模板是一个简单的单行 HTML, 其中声明了 "My First Angular App".
Now we need something to tell Angular to load this component.
现在我们需要一些东西来告诉 Angular 加载这个组件.
Give it the boot 引导该组件
Add a new file , boot.ts, to the app/ folder as follows:
添加一个新的文件, boot.ts, 到 app/ 目录, 如下所示:
We need two things to launch the application:
- Angular's browser
bootstrapfunction - The application root component that we just wrote.
我们需要做两样东西来启动该应用:
- Angualr的浏览器的引导程序
bootstrap - 我们刚刚编写的应用引导组件
We import both. Then we call bootstrap, passing in the root component type,
AppComponent.
我们引入上述两者. 然后我们调用引导程序 bootstrap, 传入引导组件类型参数 AppComponent.
Learn why we import bootstrap from angular2/platform/browser
and why we create a separate boot.ts file in the appendix below.
学习为什么从 angular2/platform/browser 中引入 bootstrap
并且为什么我们创建一个独立的文件 boot.ts, 请参考该链接 appendix below.
We've asked Angular to launch the app in a browser with our component at the root. Where will Angular put it?
我们已经告诉 Angular 在浏览器中使用我们的组件作为引导, 启动该应用. 那么 Angular 把他放到哪里了呢?
Add the index.html 增加文件 index.html
Angular displays our application in a specific location on our index.html.
It's time to create that file.
Angular 显示我们的应用到一个指定的位置, 即我们的 index.html.
是时候创建该文件了.
We won't put our index.html in the app/ folder.
We'll locate it up one level, in the project root folder.
我们将不把 index.html 放到 app/ 目录下.
而是把它道道上一级目录中, 位于项目的根目录中.
Now create the index.html file and paste the following lines:
现在创建文件 index.html, 并复制粘贴一下代码:
There are three noteworthy sections of HTML: 这里有三个HTML值得注意的部分
We load the JavaScript libraries we need.
angular2-polyfills.jsandRx.jsare needed by Angular 2.We configure something called
Systemand ask it to import the boot file we just wrote.We add the
<my-app>tag in the<body>. This is where our app lives!我们加载我们所需的 JavaScript 库.
angular2-polyfills.js和Rx.js是 Angular 2必须的.我们配置了名为
System的条目来告诉他去引入我们编写的引导文件.我们添加了标签
<my-app>在HTML页面的<body>中. 这里才是我们程序真正运行的地方!
Something has to find and load our application modules. We're using SystemJS to do that. There are other choices and we're not saying SystemJS is the best. We like it and it works.
某些东西已经找到并且加载我们的应用木块. 我们正在使用 SystemJS 做这些工作. 这里还有其他的一些选择, 我们并不是说 SystemJS 是最好的. 但是我们细化它并且它工作良好.
The specifics of SystemJS configuration are out of bounds. We'll briefly describe this particular configuration in the appendix below.
SystemJS的配置已经超出了本指南的范围. 我们将会在下面的连接中简要描述一下这种指定的配置方法, 参考 appendix below.
When Angular calls the bootstrap function in boot.ts, it reads the AppComponent
metadata, finds the my-app selector, locates an element tag named my-app,
and loads our application between those tags.
当 Angular 调用 boot.ts 文件中的 bootstrap 函数, 它将会读到 AppComponent 元数据, 发现 my-app 选择器, 然后定位一个标签名为 my-app 的元素, 最后加载我们的应用在这个标签中.
Compile and run! 编译并运行!
Open a terminal window and enter this command:
打开一个终端窗口并输入一下命令:
That command runs two parallel node processes
- The TypeScript compiler in watch mode
- A static server called lite-server that loads
index.htmlin a browser and refreshes the browser when application files change
该指令将会运行两个并行的 node 进程
- 监控模式运行 TypeScript 编译 (可以实时产看文件更新效果)
- 一个静态的服务器名为 lite-server 用来在浏览器中加载
index.html并且在文件发生更改时负责页面刷新.
In a few moments, a browser tab should open and display
等待一会, 一个浏览器的标签页将会自动打开并显示你的应用, 效果如下图

Congratulations! We are in business.
工鞋! 我们已经完成了一个简单的 Angular 2 的应用.
If you see Loading... displayed instead, see the
Browser ES6 support appendix.
如果你仅仅看到的内容为 Loading..., 请参考如下链接
Browser ES6 support appendix.
Make some changes 更改文件查看效果
Try changing the message to "My SECOND Angular 2 app".
尝试着更改信息为 "My SECOND Angular 2 app". (位于组件的 template 中)
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.
TypeScript编译器和 lite-server 在一直监控的项目文件.
他们应该检测到更改并且实时的将 TypeScript 编译为 JavaScript,
再刷新浏览器显示修改的后的内容.
It's a nifty way to develop an application!
这是一个多么棒的开发应用的方式啊!
We close the terminal window when we're done to terminate both the compiler and the server.
我们关闭终端窗口, 也就关闭了编译器和服务器.
Final structure 最终的文件目录结构
Our final project folder structure looks like this: 我们项目最终的文件目录结构如下所示:
And here are the files: 这里是这些文件内容:
Wrap Up
Our first application doesn't do much. It's basically "Hello, World" for Angular 2.
我们第一个应用没干太多事. 它也可以成为 Angular 2 的 "Hello, World".
We kept it simple in our first pass: we wrote a little Angular component,
we added some JavaScript libraries to index.html, and launched with a
static file server. That's about all we'd expect to do for a "Hello, World" app.
我们力保该应用简洁明了: 我们编写了一个小的Angular组件,
我们添加了 JavaScript 库到 index.html中, 然后启动一个静态的服务器.
这些就是创建一个 "Hello, World" 应用全部工作.
We have greater ambitions.
我们有更加雄伟的抱负
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.
好消息是一些顶层的配置基本无需我们关系.
我们将仅仅在更新库的时候才会接触 package.json.
我们也仅仅在需要添加一些库和CSS样式表文件时, 才会打开 index.html.
We're about to take the next step and build a small application that demonstrates the great things we can build with Angular 2.
我们将会进一步学习从而创建一个小的应用 来展示使用 Angular 2 所能做的.
Join us on the Tour of Heroes Tutorial! 进入我们的高级案例学习 Tour of Heroes Tutorial!
Appendices 附录
The balance of this chapter is a set of appendices that elaborate on some of the points we covered quickly above.
这一章主要是一些附录文件 详细阐述上述案例中略过的部分.
There is no essential material here. Continued reading is for the curious. 这里没有必备的材料. 如果感兴趣就继续读下去.
Appendix: Browser ES6 support 附录: 浏览器 ES6 支持.
Angular 2 relies on some ES2015 features, most of them found in modern
browsers. Some browsers (including IE 11) require a shim to support the
needed functionality.
Try loading the following shim above the other scripts in the index.html:
Angular 2 依赖于一些ES2015的特性, 大部分现代浏览器都已经支持. 一些其他浏览器 (包括 IE11) 需要shim来支持所必须的功能. (译者注:一个shim是一个库,它将一个新的API引入到一个旧的环境中,而且仅靠旧环境中已有的手段实现.)
尝试加载下面的 shim 在上面的 index.html 代码中.
Appendix: package.json 附录: package.json
npm is a popular package manager and Angular application developers rely on it to acquire and manage the libraries their apps require.
npm 是一个非常流行的包管理器, 并且 Angular 应用开发者多数依赖于它来获取和管理他们应用所需的库.
We specify the packages we need in an npm package.json file.
我们制定一个我们需的包在一个 npm 配置文件中 package.json.
The Angular team suggests the packages listed in the dependencies and devDependencies
sections listed in this file:
Angualr 团队推荐将所需要的包列在文件的两部分中 dependencies 和 devDependencies:
There are other possible package choices. We're recommending this particular set that we know work well together. Play along with us for now. Feel free to make substitutions later to suit your tastes and experience.
这里有其他可以包的选择. 我们推荐这个指定的配置因为我们知道它们工作良好. 跟我们一起玩吧 随意替换不同的包来满足您的品味和体验
A package.json has an optional scripts section where we can define helpful
commands to perform development and build tasks.
We've included a number of such scripts in our suggested package.json:
package.json 配置文件是一个可选择的 脚本 用来定义有用的指令来进行开发和构建任务.
我们已经包含了一部分脚本在我们推荐的 package.json 文件中:
We've seen how we can run the compiler and a server at the same time with this command:
我们已经看到我们如何同时运行编译器和服务器使用同一个指令:
We execute npm scripts in that manner: npm run + script-name. Here's what these scripts do:
我们还有其他方式执行 npm 脚本: npm run + 脚本名称. 这里是这些脚本的用途:
npm run tsc- run the TypeScript compiler oncenpm run tsc:w- run the TypeScript compiler in watch mode; the process keeps running, awaiting changes to TypeScript files and re-compiling when it sees them.npm run lite- run the lite-server, a light-weight, static file server, written and maintained by John Papa with excellent support for Angular apps that use routing.npm run tsc- 运行一次 TypeScript 编译器npm run tsc:w- 使用监控模式运行 TypeScript 编译器; 编译器将会保持运行, 等待 TypeScript 做出更改, 一旦检测到这些更改并重新编译npm run lite- 运行 lite-server, 这是一个轻量级的静态文件服务器, 由John Papa编写和维护. 该服务器完美支持 Angular 应用的路由机制.
Appendix: Npm errors and warnings 附录: npm 的错误和警告
All is well if there are no console messages starting with npm ERR! at the end of an npm install.
There might be a few npm WARN messages along the way — and that is perfectly fine.
在执行完 npm install 后, 如果没有输出信息带有 npm ERR!, 说明工作正常完成了.
We often see an npm WARN message after a series of gyp ERR! messages.
Ignore them. A package may try to re-compile itself using node-gyp.
If the re-compile fails, the package recovers (typically with a pre-built version)
and everything works.
我们经常看到一些警告信息 npm WARN 在一系列的 gyp ERR! 信息之后.
忽略它们吧. 一个包可以会使用 node-gyp 尝试重新自己.
如果重新编译失败, 这个包会被恢复(准确地讲是预编译版本)并且正常工作.
We are in good shape as long as there are no npm ERR! messages at the very end of npm install.
如果 npm install 之后没有 npm ERR! 消息, 一切安好!
Appendix: TypeScript configuration
We added a TypeScript configuration file (tsconfig.json) to our project to
guide the compiler as it generates JavaScript files.
Get details about tsconfig.json from the official
TypeScript wiki.
The options and flags in the file we provided are essential.
We'd like a moment to discuss the noImplicitAny flag.
TypeScript developers disagree about whether it should be true or false.
There is no correct answer and we can change the flag later.
But our choice now can make a difference in larger projects so it merits
discussion.
When the noImplicitAny flag is false,
the compiler silently defaults the type of a variable to any if it cannot infer
the type based on how the variable is used. That's what we mean by "implicitly any".
When the noImplicitAny flag is true and the TypeScript compiler cannot infer
the type, it still generates the JavaScript files but
it also reports an error.
In this QuickStart and many of the other samples in this Developer Guide
we set the noImplicitAny flag to false.
Developers who prefer stricter type checking should set the noImplicitAny flag to true.
We can still set a variable's type to any if
that seems like the best choice. We'd be doing so explicitly after
giving the matter some thought.
If we set the noImplicitAny flag to true, we may get implicit index errors as well.
If we feel these are more annoying than helpful,
we can suppress them with the following additional flag.
"suppressImplicitAnyIndexErrors":true
Appendix: SystemJS Configuration
The QuickStart uses SystemJS to load application and library modules. There are alternatives that work just fine including the well-regarded webpack. 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 here.
With those cautions in mind, what are we doing here?
The packages node 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:
Notice that the module name (after from) does not mention a filename extension.
The packages: configuration tells SystemJS to default the extension to 'js', a JavaScript file.
That makes sense because we transpile TypeScript to JavaScript before running the application.
In the live example on plunker we transpile (AKA compile) to JavaScript in the browser on the fly. That's fine for a demo. That's not our preference for development or production.
We 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.
Pre-compilation simpifies the module loading process and it's much easier to diagnose problem when this is a separate, external step.
Pre-compilation means a faster user experience because the browser doesn't waste time compiling.
We iterate development faster because we only re-compile changed files. We notice the difference as soon as the app grows beyond a handful of files.
Pre-compilation fits into a continuous integration process of build, test, deploy.
The System.import call tells SystemJS to import the boot file
(boot.js ... after transpiling boot.ts, remember?).
boot 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.
Appendix: boot.ts
Bootstrapping is platform-specific
We import the bootstrap function from angular2/platform/browser,
not angular2/core. There's a good reason.
We only call "core" those capabilities that are the same across all platform targets. True, most Angular applications run only in a browser and we'll call the bootstrap function from this library most of the time. It's pretty "core" if we're always writing for a browser.
But it is possible to load a component in a different enviroment. We might load it on a mobile device with Apache Cordova. We might wish to render the first page of our application on the server to improve launch performance or facilitate SEO.
These targets require a different kind of bootstrap function that we'd import from a different library.
Why do we create a separate boot.ts file?
The boot.ts file is tiny. This is just a QuickStart.
We could have folded its few lines into the app.component file
and spared ourselves some complexity.
We didn't for what we believe to be good reasons:
- Doing it right is easy
- Testability
- Reusability
- Separation of concerns
- We learned about import and export
It's easy
Sure it's an extra step and an extra file. How hard is that in the scheme of things?
We'll see that a separate boot.ts is beneficial for most apps
even if it isn't critical for the QuickStart.
Let's develop good habits now while the cost is low.
Testability
We should be thinking about testability from the beginning even if we know we'll never test the QuickStart.
It is difficult to unit test a component when there is a call to bootstrap in the same file.
As soon as we load the component file to test the component,
the bootstrap function tries to load the application in the browser.
It throws an error because we're not expecting to run the entire application,
just test the component.
Relocating the bootstrap function to boot.ts eliminates this spurious error
and leaves us with a clean component module file.
Reusability
We refactor, rename, and relocate files as our application evolves.
We can't do any of those things while the file calls bootstrap.
We can't move it.
We can't reuse the component in another application.
We can't pre-render the component on the server for better performance.
Separation of concerns
A component's responsibility is to present and manage a view.
Launching the application has nothing to do with view management. That's a separate concern. The friction we're encountering in testing and reuse stems from this unnecessary mix of responsibilities.
Import/Export
While writing a separate boot.ts file we learned an essential Angular skill:
how to export from one module and import into another.
We'll do a lot of that as we learn more Angular.