Angular is a framework for building client applications in HTML and
either JavaScript or a language like TypeScript that compiles to JavaScript.
该框架包括一系列库,有些是核心库,有些是可选库。
The framework consists of several libraries, some of them core and some optional.
我们是这样写 Angular 应用的:用 Angular 扩展语法编写 HTML 模板,
用组件类管理这些模板,用服务添加应用逻辑,
用模块打包发布组件与服务。
You write Angular applications by composing HTML templates with Angularized markup,
writing component classes to manage those templates, adding application logic in services,
and boxing components and services in modules.
Then you launch the app by bootstrapping the root module.
Angular takes over, presenting your application content in a browser and
responding to user interactions according to the instructions you've provided.
当然,这只是冰山一角。后面我们将学习更多的细节。不过,目前我们还是先关注全景图吧。
Of course, there is more to it than this.
You'll learn the details in the pages that follow. For now, focus on the big picture.
这个架构图展现了 Angular 应用中的 8 个主要构造块:
The architecture diagram identifies the eight main building blocks of an Angular application:
While the root module may be the only module in a small application, most apps have many more
feature modules, each a cohesive block of code dedicated to an application domain,
a workflow, or a closely related set of capabilities.
Angular 模块(无论是根模块还是特性模块)都是一个带有@NgModule装饰器的类。
An Angular module, whether a root or feature, is a class with an @NgModule decorator.
Decorators are functions that modify JavaScript classes.
Angular has many decorators that attach metadata to classes so that it knows
what those classes mean and how they should work.
Learn more about decorators on the web.
NgModule是一个装饰器函数,它接收一个用来描述模块属性的元数据对象。其中最重要的属性是:
NgModule is a decorator function that takes a single metadata object whose properties describe the module.
The most important properties are:
bootstrap - the main application view, called the root component,
that hosts all other app views. Only the root module should set this bootstrap property.
The export of AppComponent is just to show how to export; it isn't actually necessary in this example. A root module has no reason to export anything because other components don't need to import the root module.
JavaScript also has its own module system for managing collections of JavaScript objects.
It's completely different and unrelated to the Angular module system.
In JavaScript each file is a module and all objects defined in the file belong to that module.
The module declares some objects to be public by marking them with the export key word.
Other JavaScript modules use import statements to access public objects from other modules.
In the example of the simple root module above, the application module needs material from within that BrowserModule. To access that material, add it to the @NgModule metadata imports like this.
imports:[BrowserModule],
这种情况下,你同时使用了 Angular 和 JavaScript 的模块化系统。
In this way you're using both the Angular and JavaScript module systems together.
It's easy to confuse the two systems because they share the common vocabulary of "imports" and "exports".
Hang in there. The confusion yields to clarity with time and experience.
A component controls a patch of screen called a view.
例如,下列视图都是由组件控制的:
For example, the following views are controlled by components:
带有导航链接的应用根组件。
The app root with the navigation links.
英雄列表。
The list of heroes.
英雄编辑器。
The hero editor.
我们在类中定义组件的应用逻辑,为视图提供支持。
组件通过一些由属性和方法组成的 API 与视图交互。
You 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.
For example, this HeroListComponent has a heroes property that returns an array of heroes
that it acquires from a service.
HeroListComponent also has a selectHero() method that sets a selectedHero property when the user clicks to choose a hero from that list.
Angular creates, updates, and destroys components as the user moves through the application.
Your app can take action at each moment in this lifecycle through optional lifecycle hooks, like ngOnInit() declared above.
模板
Templates
我们通过组件的自带的模板来定义组件视图。模板以 HTML 形式存在,告诉 Angular 如何渲染组件。
You define a component's view with its companion template. A template is a form of HTML
that tells Angular how to render the component.
模板除了可以使用像<h2>和<p>这样的典型的 HTML 元素,还能使用其它元素。
例如,像*ngFor、{{hero.name}}、(click)、[hero]和<hero-detail>这样的代码使用了 Angular 的模板语法。
Although this template uses typical HTML elements like <h2> and <p>, it also has some differences. Code like *ngFor, {{hero.name}}, (click), [hero], and <hero-detail> uses Angular's template syntax.
The HeroDetailComponent is a different component than the HeroListComponent you've been reviewing.
The HeroDetailComponent (code not shown) presents facts about a particular hero, the
hero that the user selects from the list presented by the HeroListComponent.
The HeroDetailComponent is a child of the HeroListComponent.
注意到了吗?<hero-detail>舒适地躺在原生 HTML 元素之间。
自定义组件和原生 HTML 在同一布局中融合得天衣无缝。
Notice how <hero-detail> rests comfortably among native HTML elements. Custom components mix seamlessly with native HTML in the same layouts.
The @Component decorator takes a required configuration object with the
information Angular needs to create and present the component and its view.
@Component的配置项包括:
Here are a few of the most useful @Component configuration options:
selector: CSS 选择器,它告诉 Angular 在父级 HTML 中查找<hero-list>标签,创建并插入该组件。
例如,如果应用的 HTML 包含<hero-list></hero-list>, Angular 就会把HeroListComponent的一个实例插入到这个标签中。
selector: CSS selector that tells Angular to create and insert an instance of this component
where it finds a <hero-list> tag in parent HTML.
For example, if an app's HTML contains <hero-list></hero-list>, then
Angular inserts an instance of the HeroListComponent view between those tags.
providers: array of dependency injection providers for services that the component requires.
This is one way to tell Angular that the component's constructor requires a HeroService
so it can get the list of heroes to display.
@Component里面的元数据会告诉 Angular 从哪里获取你为组件指定的主要的构建块。
The metadata in the @Component tells Angular where to get the major building blocks you specify for the component.
模板、元数据和组件共同描绘出这个视图。
The template, metadata, and component together describe a view.
Apply other metadata decorators in a similar fashion to guide Angular behavior.
@Injectable, @Input, and @Output are a few of the more popular decorators.
这种架构处理方式是:你向代码中添加元数据,以便 Angular 知道该怎么做。
The architectural takeaway is that you must add metadata to your code
so that Angular knows what to do.
数据绑定
Data binding
如果没有框架,我们就得自己把数据值推送到 HTML 控件中,并把用户的反馈转换成动作和值更新。
如果手工写代码来实现这些推/拉逻辑,肯定会枯燥乏味、容易出错,读起来简直是噩梦 —— 写过 jQuery 的程序员大概都对此深有体会。
Without a framework, you would be responsible for pushing data values into the HTML controls and turning user responses
into actions and value updates. Writing such push/pull logic by hand is tedious, error-prone, and a nightmare to
read as any experienced jQuery programmer can attest.
Angular 支持数据绑定,一种让模板的各部分与组件的各部分相互合作的机制。
我们往模板 HTML 中添加绑定标记,来告诉 Angular 如何把二者联系起来。
Angular supports data binding,
a mechanism for coordinating parts of a template with parts of a component.
Add binding markup to the template HTML to tell Angular how to connect both sides.
如图所示,数据绑定的语法有四种形式。每种形式都有一个方向 —— 绑定到 DOM 、绑定自 DOM 以及双向绑定。
As the diagram shows, there are four forms of data binding syntax. Each form has a direction — to the DOM, from the DOM, or in both directions.
Two-way data binding is an important fourth form
that combines property and event binding in a single notation, using the ngModel directive.
Here's an example from the HeroDetailComponent template:
In two-way binding, a data property value flows to the input box from the component as with property binding.
The user's changes also flow back to the component, resetting the property to the latest value,
as with event binding.
A directive is a class with a @Directive decorator.
A component is a directive-with-a-template;
a @Component decorator is actually a @Directive decorator extended with template-oriented features.
While a component is technically a directive,
components are so distinctive and central to Angular applications that this architectural overview separates components from directives.
还有两种其它类型的指令:结构型指令和属性 (attribute) 型指令。
Two other kinds of directives exist: structural and attribute directives.
The ngModel directive, which implements two-way data binding, is
an example of an attribute directive. ngModel modifies the behavior of
an existing element (typically an <input>)
by setting its display value property and responding to change events.
Angular has a few more directives that either alter the layout structure
(for example, ngSwitch)
or modify aspects of DOM elements and components
(for example, ngStyle and ngClass).
当然,我们也能编写自己的指令。像HeroListComponent这样的组件就是一种自定义指令。
Of course, you can also write your own directives. Components such as
HeroListComponent are one kind of custom directive.
服务
Services
服务是一个广义范畴,包括:值、函数,或应用所需的特性。
Service is a broad category encompassing any value, function, or feature that your application needs.
There is nothing specifically Angular about services. Angular has no definition of a service.
There is no service base class, and no place to register a service.
即便如此,服务仍然是任何 Angular 应用的基础。组件就是最大的服务消费者。
Yet services are fundamental to any Angular application. Components are big consumers of services.
下面是一个服务类的范例,用于把日志记录到浏览器的控制台:
Here's an example of a service class that logs to the browser console:
Here's a HeroService that uses a Promise to fetch heroes.
The HeroService depends on the Logger service and another BackendService that handles the server communication grunt work.
src/app/hero.service.ts (class)
exportclassHeroService{private heroes:Hero[]=[];
constructor(private backend:BackendService,private logger:Logger){}
getHeroes(){this.backend.getAll(Hero).then((heroes:Hero[])=>{this.logger.log(`Fetched ${heroes.length} heroes.`);this.heroes.push(...heroes);// fill cache});returnthis.heroes;}}
Component classes should be lean. They don't fetch data from the server,
validate user input, or log directly to the console.
They delegate such tasks to services.
A component's job is to enable the user experience and nothing more. It mediates between the view (rendered by the template)
and the application logic (which often includes some notion of a model).
A good component presents properties and methods for data binding.
It delegates everything nontrivial to services.
Angular does help you follow these principles by making it easy to factor your
application logic into services and make those services available to components through dependency injection.
Dependency injection is a way to supply a new instance of a class
with the fully-formed dependencies it requires. Most dependencies are services.
Angular uses dependency injection to provide new components with the services they need.
Angular can tell which services a component needs by looking at the types of its constructor parameters.
For example, the constructor of your HeroListComponent needs a HeroService:
src/app/hero-list.component.ts (constructor)
constructor(private service:HeroService){}
当 Angular 创建组件时,会首先为组件所需的服务请求一个注入器 (injector)。
When Angular creates a component, it first asks an injector for
the services that the component requires.
An injector maintains a container of service instances that it has previously created.
If a requested service instance is not in the container, the injector makes one and adds it to the container
before returning the service to Angular.
When all requested services have been resolved and returned,
Angular can call the component's constructor with those services as arguments.
This is dependency injection.
HeroService注入的过程差不多是这样的:
The process of HeroService injection looks a bit like this:
如果注入器还没有HeroService,它怎么知道该如何创建一个呢?
If the injector doesn't have a HeroService, how does it know how to make one?
In brief, you must have previously registered a provider of the HeroService with the injector.
A provider is something that can create or return a service, typically the service class itself.
我们可以在模块中或组件中注册提供商。
You can register providers in modules or in components.
That's a foundation for everything else in an Angular application,
and it's more than enough to get going.
But it doesn't include everything you need to know.
Change detection: The change detection documentation will cover how Angular decides that a component property value has changed,
when to update the screen, and how it uses zones to intercept asynchronous activity and run its change detection strategies.
事件:事件文档会告诉你如何使用组件和服务触发支持发布和订阅的事件。
Events: The events documentation will cover how to use components and services to raise events with mechanisms for
publishing and subscribing to events.
Lifecycle hooks: Tap into key moments in the lifetime of a component, from its creation to its destruction,
by implementing the lifecycle hook interfaces.