From 51bd5988264d453d3616f58c14a4cd65e2098784 Mon Sep 17 00:00:00 2001 From: Zhicheng Wang Date: Wed, 7 Mar 2018 10:51:31 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E6=AD=A3=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E7=BF=BB=E8=AF=91=E7=BB=93=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- aio/content/guide/ajs-quick-reference.md | 61 ++ aio/content/guide/animations.md | 2 + aio/content/guide/aot-compiler.md | 16 + aio/content/guide/api-page-class.md | 46 +- aio/content/guide/attribute-directives.md | 15 +- aio/content/guide/bootstrapping.md | 3 + aio/content/guide/browser-support.md | 23 +- aio/content/guide/change-log.md | 4 +- aio/content/guide/cheatsheet.md | 547 +++++++++++++----- aio/content/guide/comparing-observables.md | 231 +++++--- aio/content/guide/component-interaction.md | 19 +- aio/content/guide/component-styles.md | 7 +- .../guide/dependency-injection-in-action.md | 33 +- .../guide/dependency-injection-pattern.md | 3 +- aio/content/guide/dependency-injection.md | 17 +- aio/content/guide/deployment.md | 7 +- aio/content/guide/displaying-data.md | 13 +- aio/content/guide/docs-style-guide.md | 265 +++++---- 18 files changed, 854 insertions(+), 458 deletions(-) diff --git a/aio/content/guide/ajs-quick-reference.md b/aio/content/guide/ajs-quick-reference.md index 637a5382db..820aea7421 100644 --- a/aio/content/guide/ajs-quick-reference.md +++ b/aio/content/guide/ajs-quick-reference.md @@ -62,7 +62,9 @@ The following table lists some of the key AngularJS template features with their ### 绑定/插值表达式 + Your favorite hero is: {{vm.favoriteHero}} + In AngularJS, an expression in curly braces denotes one-way binding. @@ -116,7 +118,9 @@ The following table lists some of the key AngularJS template features with their ### 过滤器 + <td>{{movie.title | uppercase}}</td> + To filter output in AngularJS templates, use the pipe character (|) and one or more filters. @@ -161,9 +165,11 @@ The following table lists some of the key AngularJS template features with their ### 局部变量 + <tr ng-repeat="movie in vm.movies"> <td>{{movie.title}}</td> </tr> + Here, `movie` is a user-defined local variable. @@ -240,7 +246,9 @@ AngularJS 为模板提供了七十多个内置指令。 ### ng-app + <body ng-app="movieHunter"> + The application startup process is called **bootstrapping**. @@ -263,6 +271,7 @@ AngularJS 为模板提供了七十多个内置指令。 ### 引导 +
@@ -286,9 +295,11 @@ AngularJS 为模板提供了七十多个内置指令。 ### ng-class + <div ng-class="{active: isActive}"> <div ng-class="{active: isActive, shazam: isImportant}"> + In AngularJS, the `ng-class` directive includes/excludes CSS classes @@ -350,8 +361,10 @@ AngularJS 为模板提供了七十多个内置指令。 ### ng-click + <button ng-click="vm.toggleImage()"> <button ng-click="vm.toggleImage($event)"> + In AngularJS, the `ng-click` directive allows you to specify custom behavior when an element is clicked. @@ -420,7 +433,9 @@ AngularJS 为模板提供了七十多个内置指令。 ### ng-controller + <div ng-controller="MovieListCtrl as vm"> + In AngularJS, the `ng-controller` directive attaches a controller to the view. @@ -491,7 +506,9 @@ AngularJS 为模板提供了七十多个内置指令。 ### ng-href + <a ng-href="{{ angularDocsUrl }}">Angular Docs</a> + The `ng-href` directive allows AngularJS to preprocess the `href` property so that it @@ -505,7 +522,9 @@ AngularJS 为模板提供了七十多个内置指令。 在AngularJS 中,`ng-href`通常用来作为导航的一部分,激活一个路由。 + <a ng-href="#{{ moviesHash }}">Movies</a> + Routing is handled differently in Angular. @@ -555,7 +574,9 @@ AngularJS 为模板提供了七十多个内置指令。 ### ng-if + <table ng-if="movies.length"> + In AngularJS, the `ng-if` directive removes or recreates a portion of the DOM, @@ -602,7 +623,9 @@ AngularJS 为模板提供了七十多个内置指令。 ### ng-model + <input ng-model="vm.favoriteHero"/> + In AngularJS, the `ng-model` directive binds a form control to a property in the controller associated with the template. @@ -642,7 +665,9 @@ AngularJS 为模板提供了七十多个内置指令。 ### ng-repeat + <tr ng-repeat="movie in vm.movies"> + In AngularJS, the `ng-repeat` directive repeats the associated DOM element @@ -694,9 +719,11 @@ AngularJS 为模板提供了七十多个内置指令。 ### ng-show + <h3 ng-show="vm.favoriteHero"> Your favorite hero is: {{vm.favoriteHero}} </h3> + In AngularJS, the `ng-show` directive shows or hides the associated DOM element, based on @@ -749,7 +776,9 @@ AngularJS 为模板提供了七十多个内置指令。 ### ng-src + <img ng-src="{{movie.imageurl}}"> + The `ng-src` directive allows AngularJS to preprocess the `src` property so that it @@ -790,7 +819,9 @@ AngularJS 为模板提供了七十多个内置指令。 ### ng-style + <div ng-style="{color: colorPreference}"> + In AngularJS, the `ng-style` directive sets a CSS style on an HTML element @@ -846,6 +877,7 @@ AngularJS 为模板提供了七十多个内置指令。 ### ng-switch + <div ng-switch="vm.favoriteHero && vm.checkMovieHero(vm.favoriteHero)"> <div ng-switch-when="true"> @@ -858,6 +890,7 @@ AngularJS 为模板提供了七十多个内置指令。 Please enter your favorite hero. </div> </div> + In AngularJS, the `ng-switch` directive swaps the contents of @@ -963,7 +996,9 @@ AngularJS中的很多内置过滤器在Angular中都有对应的管道。 ### currency + <td>{{movie.price | currency}}</td> + Formats a number as currency. @@ -993,7 +1028,9 @@ AngularJS中的很多内置过滤器在Angular中都有对应的管道。 ### date + <td>{{movie.releaseDate | date}}</td> + Formats a date to a string based on the requested format. @@ -1023,7 +1060,9 @@ AngularJS中的很多内置过滤器在Angular中都有对应的管道。 ### filter + <tr ng-repeat="movie in movieList | filter: {title:listFilter}"> + Selects a subset of items from the defined collection, based on the filter criteria. @@ -1055,7 +1094,9 @@ AngularJS中的很多内置过滤器在Angular中都有对应的管道。 ### json + <pre>{{movie | json}}</pre> + Converts a JavaScript object into a JSON string. This is useful for debugging. @@ -1085,7 +1126,9 @@ AngularJS中的很多内置过滤器在Angular中都有对应的管道。 ### limitTo + <tr ng-repeat="movie in movieList | limitTo:2:0"> + Selects up to the first parameter (2) number of items from the collection @@ -1121,7 +1164,9 @@ AngularJS中的很多内置过滤器在Angular中都有对应的管道。 ### lowercase + <div>{{movie.title | lowercase}}</div> + Converts the string to lowercase. @@ -1151,7 +1196,9 @@ AngularJS中的很多内置过滤器在Angular中都有对应的管道。 ### number + <td>{{movie.starRating | number}}</td> + Formats a number as text. @@ -1189,7 +1236,9 @@ AngularJS中的很多内置过滤器在Angular中都有对应的管道。 ### orderBy + <tr ng-repeat="movie in movieList | orderBy : 'title'"> + Displays the collection in the order specified by the expression. @@ -1273,9 +1322,11 @@ The Angular code is shown using TypeScript. ### IIFE + (function () { ... }()); + In AngularJS, an immediately invoked function expression (or IIFE) around controller code @@ -1314,7 +1365,9 @@ The Angular code is shown using TypeScript. ### Angular模块 + angular.module("movieHunter", ["ngRoute"]); + In AngularJS, an Angular module keeps track of controllers, services, and other code. @@ -1359,11 +1412,13 @@ The Angular code is shown using TypeScript. ### 控制器注册 + angular .module("movieHunter") .controller("MovieListCtrl", ["movieService", MovieListCtrl]); + AngularJS has code in each controller that looks up an appropriate Angular module @@ -1415,8 +1470,10 @@ The Angular code is shown using TypeScript. ### 控制器函数 + function MovieListCtrl(movieService) { } + In AngularJS, you write the code for the model and methods in a controller function. @@ -1459,9 +1516,11 @@ The Angular code is shown using TypeScript. ### 依赖注入 + MovieListCtrl.$inject = ['MovieService']; function MovieListCtrl(movieService) { } + In AngularJS, you pass in any dependencies as controller function arguments. @@ -1557,7 +1616,9 @@ also encapsulate a style sheet within a specific component. ### Link 标签 + <link href="styles.css" rel="stylesheet" /> + AngularJS, uses a `link` tag in the head section of the `index.html` file diff --git a/aio/content/guide/animations.md b/aio/content/guide/animations.md index 9423f2ac1e..e822e42b3f 100644 --- a/aio/content/guide/animations.md +++ b/aio/content/guide/animations.md @@ -277,8 +277,10 @@ These two common animations have their own aliases: 这两个常见的动画有自己的别名: + transition(':enter', [ ... ]); // void => * transition(':leave', [ ... ]); // * => void + diff --git a/aio/content/guide/aot-compiler.md b/aio/content/guide/aot-compiler.md index 2f72c86c9a..36e4d6de9f 100644 --- a/aio/content/guide/aot-compiler.md +++ b/aio/content/guide/aot-compiler.md @@ -35,8 +35,10 @@ Angular offers two ways to compile your application: JIT compilation is the default when you run the _build-only_ or the _build-and-serve-locally_ CLI commands: + ng build ng serve + {@a compile} @@ -44,8 +46,10 @@ JIT compilation is the default when you run the _build-only_ or the _build-and-s For AOT compilation, append the `--aot` flags to the _build-only_ or the _build-and-serve-locally_ CLI commands: + ng build --aot ng serve --aot +
@@ -1085,6 +1089,7 @@ import { calculateValue } from './utilities'; To correct this error, export a function from the module and refer to the function in a `useFactory` provider instead. + // CORRECTED import { calculateValue } from './utilities'; @@ -1100,6 +1105,7 @@ export function someValueFactory() { { provide: SomeValue, useFactory: someValueFactory } ] ... +
@@ -1119,6 +1125,7 @@ The compiler does not support references to variables assigned by [destructuring For example, you cannot write something like this: + // ERROR import { configuration } from './configuration'; @@ -1130,11 +1137,13 @@ const {foo, bar} = configuration; {provide: Bar, useValue: bar}, ] ... + To correct this error, refer to non-destructured values. + // CORRECTED import { configuration } from './configuration'; ... @@ -1143,6 +1152,7 @@ import { configuration } from './configuration'; {provide: Bar, useValue: configuration.bar}, ] ... +
@@ -1188,6 +1198,7 @@ you can finesse the problem in four steps: Here's an illustrative example. + // CORRECTED import { Inject } from '@angular/core'; @@ -1203,6 +1214,7 @@ export function _window() { return window; } export class MyComponent { constructor (@Inject(WINDOW) private win: Window) { ... } } + The `Window` type in the constructor is no longer a problem for the compiler because it @@ -1211,6 +1223,7 @@ uses the `@Inject(WINDOW)` to generate the injection code. Angular does something similar with the `DOCUMENT` token so you can inject the browser's `document` object (or an abstraction of it, depending upon the platform in which the application runs). + import { Inject } from '@angular/core'; import { DOCUMENT } from '@angular/platform-browser'; @@ -1218,6 +1231,7 @@ import { DOCUMENT } from '@angular/platform-browser'; export class MyComponent { constructor (@Inject(DOCUMENT) private doc: Document) { ... } } +
@@ -1253,6 +1267,7 @@ that you referenced in metadata. The compiler can understand simple enum values but not complex values such as those derived from computed properties. + // ERROR enum Colors { Red = 1, @@ -1267,6 +1282,7 @@ enum Colors { { provide: StrongColor, useValue: Colors.Blue } // bad ] ... + Avoid referring to enums with complicated initializers or computed properties. diff --git a/aio/content/guide/api-page-class.md b/aio/content/guide/api-page-class.md index 990ecd9c21..2a5c03d2e4 100644 --- a/aio/content/guide/api-page-class.md +++ b/aio/content/guide/api-page-class.md @@ -6,7 +6,7 @@
-

Class Name

+

Class Name

@@ -19,7 +19,7 @@

- Class description goes here. This is a short and to the point one or two sentence description that easily introduces the reader to the class. +Class description goes here. This is a short and to the point one or two sentence description that easily introduces the reader to the class.

@@ -47,9 +47,9 @@

- The longer class description goes here which can include multiple paragraphs. +The longer class description goes here which can include multiple paragraphs. -

+

Bacon ipsum dolor amet pork belly capicola sirloin venison alcatra ground round ham hock jowl turkey picanha bresaola pancetta brisket chicken fatback. Burgdoggen kevin salami jowl shoulder jerky leberkas meatball. Ham hock picanha burgdoggen pork belly rump bacon cupim. Bacon kielbasa sirloin shank strip steak ground round. Bresaola cow salami meatloaf pork chop leberkas flank turducken biltong meatball chuck pork tri-tip chicken. Ribeye corned beef shoulder, meatloaf strip steak jerky porchetta capicola alcatra ham.

@@ -100,6 +100,7 @@

Constructor

+
   
         constructor(element: any, keyframes: {
         [key: string]: string | number;
@@ -242,17 +243,17 @@
 
             

- Description goes here +Description goes here -

+


- Bacon ipsum dolor amet pork belly capicola sirloin venison alcatra ground round ham hock jowl turkey picanha bresaola pancetta brisket chicken fatback. Burgdoggen kevin salami jowl shoulder jerky leberkas meatball. Ham hock picanha burgdoggen pork belly rump bacon cupim. Bacon kielbasa sirloin shank strip steak ground round. Bresaola cow salami meatloaf pork chop leberkas flank turducken biltong meatball chuck pork tri-tip chicken. Ribeye corned beef shoulder, meatloaf strip steak jerky porchetta capicola alcatra ham. +Bacon ipsum dolor amet pork belly capicola sirloin venison alcatra ground round ham hock jowl turkey picanha bresaola pancetta brisket chicken fatback. Burgdoggen kevin salami jowl shoulder jerky leberkas meatball. Ham hock picanha burgdoggen pork belly rump bacon cupim. Bacon kielbasa sirloin shank strip steak ground round. Bresaola cow salami meatloaf pork chop leberkas flank turducken biltong meatball chuck pork tri-tip chicken. Ribeye corned beef shoulder, meatloaf strip steak jerky porchetta capicola alcatra ham. -

+

@@ -282,18 +283,20 @@

- Description goes here +Description goes here -

+


Declaration
+
                     class AnimationBuilder {build(animation: AnimationMetadata | AnimationMetadata[]): AnimationFactory}
+
Parameters
@@ -302,17 +305,17 @@

- Returns information and results goes here. +Returns information and results goes here. -

+

Errors

- Error information goes here +Error information goes here -

+


@@ -327,6 +330,7 @@ +
   
         constructor(element: any, keyframes: {
         [key: string]: string | number;
@@ -347,6 +351,7 @@
                 
 
                     
+
         
   
         constructor(element: any, keyframes: {
         [key: string]: string | number;
@@ -371,9 +376,9 @@
 
             

- Bacon ipsum dolor amet pork belly capicola sirloin venison alcatra ground round ham hock jowl turkey picanha bresaola pancetta brisket chicken fatback. Burgdoggen kevin salami jowl shoulder jerky leberkas meatball. Ham hock picanha burgdoggen pork belly rump bacon cupim. Bacon kielbasa sirloin shank strip steak ground round. Bresaola cow salami meatloaf pork chop leberkas flank turducken biltong meatball chuck pork tri-tip chicken. Ribeye corned beef shoulder, meatloaf strip steak jerky porchetta capicola alcatra ham. +Bacon ipsum dolor amet pork belly capicola sirloin venison alcatra ground round ham hock jowl turkey picanha bresaola pancetta brisket chicken fatback. Burgdoggen kevin salami jowl shoulder jerky leberkas meatball. Ham hock picanha burgdoggen pork belly rump bacon cupim. Bacon kielbasa sirloin shank strip steak ground round. Bresaola cow salami meatloaf pork chop leberkas flank turducken biltong meatball chuck pork tri-tip chicken. Ribeye corned beef shoulder, meatloaf strip steak jerky porchetta capicola alcatra ham. -

+

@@ -387,11 +392,12 @@

- Intro description text about what the example is and how it can be used. +Intro description text about what the example is and how it can be used. -

+

+
   
         constructor(element: any, keyframes: {
         [key: string]: string | number;
@@ -400,9 +406,9 @@
 
         

- Further explanation provided as needed. Bacon ipsum dolor amet pork belly capicola sirloin venison alcatra ground round ham hock jowl turkey picanha bresaola pancetta brisket chicken fatback. Burgdoggen kevin salami jowl shoulder jerky leberkas meatball. +Further explanation provided as needed. Bacon ipsum dolor amet pork belly capicola sirloin venison alcatra ground round ham hock jowl turkey picanha bresaola pancetta brisket chicken fatback. Burgdoggen kevin salami jowl shoulder jerky leberkas meatball. -

+

diff --git a/aio/content/guide/attribute-directives.md b/aio/content/guide/attribute-directives.md index 819a74b7f1..d996857d5c 100644 --- a/aio/content/guide/attribute-directives.md +++ b/aio/content/guide/attribute-directives.md @@ -280,9 +280,7 @@ the mouse hovers over the `p` and disappears as it moves out. 运行本应用并确认:当把鼠标移到`p`上的时候,背景色就出现了,而移开的时候,它消失了。
- Second Highlight -
{@a bindings} @@ -437,9 +435,7 @@ Here are the harness and directive in action. 下面是测试程序和指令的动图。
- Highlight v.2 -
{@a second-property} @@ -494,9 +490,7 @@ Here's how the harness should work when you're done coding. 当这些代码完成时,测试程序工作时的动图如下:
- Final Highlight -
## Summary @@ -528,19 +522,12 @@ The final source code follows: 最终的源码如下: - - - - - - - You can also experience and download the . @@ -635,4 +622,4 @@ Now apply that reasoning to the following example: `myHighlight`属性位于左侧,它引用了`MyHighlightDirective`中一个*带别名的*属性,它不是模板所属组件的一部分,因此存在信任问题。 -所以,该属性必须带`@Input`装饰器。 \ No newline at end of file +所以,该属性必须带`@Input`装饰器。 diff --git a/aio/content/guide/bootstrapping.md b/aio/content/guide/bootstrapping.md index f3bd1318ca..6d277083a5 100644 --- a/aio/content/guide/bootstrapping.md +++ b/aio/content/guide/bootstrapping.md @@ -16,6 +16,7 @@ By convention, it is usually called `AppModule`. If you use the CLI to generate an app, the default `AppModule` is as follows: ```typescript + /* JavaScript imports */ import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; @@ -83,11 +84,13 @@ this module and the other module imports this one. An example of what goes into a declarations array follows: ```typescript + declarations: [ YourComponent, YourPipe, YourDirective ], + ``` A declarable can only belong to one module, so only declare it in diff --git a/aio/content/guide/browser-support.md b/aio/content/guide/browser-support.md index 0b73bdeebb..346e1c3e46 100644 --- a/aio/content/guide/browser-support.md +++ b/aio/content/guide/browser-support.md @@ -81,7 +81,6 @@ Angular 支持大多数常用浏览器,包括下列版本: - @@ -97,9 +96,7 @@ Angular 支持大多数常用浏览器,包括下列版本: - - @@ -115,7 +112,6 @@ Angular 支持大多数常用浏览器,包括下列版本: - @@ -133,7 +129,6 @@ Angular 支持大多数常用浏览器,包括下列版本: - @@ -151,7 +146,6 @@ Angular 支持大多数常用浏览器,包括下列版本: - @@ -235,7 +229,9 @@ For example, [if you need the web animations polyfill](http://caniuse.com/#feat= # note that the web-animations-js polyfill is only here as an example + # it isn't a strict requirement of Angular anymore (more below) + npm install --save web-animations-js @@ -247,7 +243,9 @@ Then open the `polyfills.ts` file and un-comment the corresponding `import` stat /** + * Required to support Web Animations `@angular/platform-browser/animations`. + * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation **/ import 'web-animations-js'; // Run `npm install --save web-animations-js`. @@ -438,12 +436,10 @@ Here are the features which may require additional polyfills: [Animations](guide/animations) - - [动画](guide/animations) -
Only if `Animation Builder` is used within the application--standard animation support in Angular doesn't require any polyfills (as of NG6). + [动画](guide/animations)
只有在应用中用到了 `Animation Builder` 时才需要;Angular 标准的动画支持是不需要任何腻子脚本的(截至 NG6)。 @@ -541,13 +537,9 @@ Here are the features which may require additional polyfills: - [Typed Array](guide/browser-support#typedarray) + [Typed Array](guide/browser-support#typedarray)
-
- - [Blob](guide/browser-support#blob) - -
+ [Blob](guide/browser-support#blob)
[FormData](guide/browser-support#formdata) @@ -828,4 +820,3 @@ If you are not using the CLI, you should add your polyfill scripts directly to t <!-- application polyfills -->
- diff --git a/aio/content/guide/change-log.md b/aio/content/guide/change-log.md index 9f8ae96007..02c843f8cc 100644 --- a/aio/content/guide/change-log.md +++ b/aio/content/guide/change-log.md @@ -140,7 +140,7 @@ Revised samples are clearer and cover all topics discussed. * [Setup](guide/setup) guide: added (optional) instructions on how to remove _non-essential_ files. - [环境搭建](guide/setup)指南: + [环境搭建](guide/setup)指南: 添加了(可选的)步骤说明,告诉你如何移除*非核心*文件。 * No longer consolidate RxJS operator imports in `rxjs-extensions` file; each file should import what it needs. @@ -429,4 +429,4 @@ The [Lifecycle Hooks](guide/lifecycle-hooks) guide is shorter, simpler, and draws more attention to the order in which Angular calls the hooks. -[生命周期钩子](guide/lifecycle-hooks)章现在更加简短,并且对强调了Angular是以什么顺序来调用钩子方法的。 \ No newline at end of file +[生命周期钩子](guide/lifecycle-hooks)章现在更加简短,并且对强调了Angular是以什么顺序来调用钩子方法的。 diff --git a/aio/content/guide/cheatsheet.md b/aio/content/guide/cheatsheet.md index 7da15c03a6..8fbfcf5fd3 100644 --- a/aio/content/guide/cheatsheet.md +++ b/aio/content/guide/cheatsheet.md @@ -1,52 +1,59 @@ - -

Cheat Sheet

- - + - - + -
Bootstrapping + + Bootstrapping + +

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; -

platformBrowserDynamic().bootstrapModule(AppModule); + + platformBrowserDynamic().bootstrapModule(AppModule); + +

Bootstraps the app, using the root component from the specified NgModule.

- - + - - + - + - + - + - + - + -
NgModules + + NgModules + +

import { NgModule } from '@angular/core'; -

@NgModule({ declarations: ..., imports: ...,
exports: ..., providers: ..., bootstrap: ...})
class MyModule {}
+ + @NgModule({ declarations: ..., imports: ...,
exports: ..., providers: ..., bootstrap: ...})
class MyModule {}
+ +

Defines a module that contains components, directives, pipes, and providers.

@@ -54,7 +61,11 @@
declarations: [MyRedComponent, MyBlueComponent, MyDatePipe] + + declarations: [MyRedComponent, MyBlueComponent, MyDatePipe] + +

List of components, directives, and pipes that belong to this module.

@@ -62,18 +73,24 @@
imports: [BrowserModule, SomeOtherModule] + + imports: [BrowserModule, SomeOtherModule] + +

List of modules to import into this module. Everything from the imported modules -is available to - - declarations of this module.

+is available to declarations of this module.

exports: [MyRedComponent, MyDatePipe] + + exports: [MyRedComponent, MyDatePipe] + +

List of components, directives, and pipes visible to modules that import this module.

@@ -81,7 +98,11 @@ is available to
providers: [MyService, { provide: ... }] + + providers: [MyService, { provide: ... }] + +

List of dependency injection providers visible both to the contents of this module and to importers of this module.

@@ -89,29 +110,42 @@ is available to
bootstrap: [MyAppComponent] + + bootstrap: [MyAppComponent] + +

List of components to bootstrap when this module is bootstrapped.

- - + + Template syntax + + 模板语法 + + + + - - + - + - + - + - + - + - + - + - + - + - + - + - + - + -
Template syntax - + +
<input [value]="firstName"> + + <input [value]="firstName"> + +

Binds property value to the result of expression firstName.

@@ -119,7 +153,11 @@ is available to
<div [attr.role]="myAriaRole"> + + <div [attr.role]="myAriaRole"> + +

Binds attribute role to the result of expression myAriaRole.

@@ -127,7 +165,11 @@ is available to
<div [class.extra-sparkle]="isDelightful"> + + <div [class.extra-sparkle]="isDelightful"> + +

Binds the presence of the CSS class extra-sparkle on the element to the truthiness of the expression isDelightful.

@@ -135,7 +177,11 @@ is available to
<div [style.width.px]="mySize"> + + <div [style.width.px]="mySize"> + +

Binds style property width to the result of expression mySize in pixels. Units are optional.

@@ -143,7 +189,11 @@ is available to
<button (click)="readRainbow($event)"> + + <button (click)="readRainbow($event)"> + +

Calls method readRainbow when a click event is triggered on this button element (or its children) and passes in the event object.

@@ -151,17 +201,24 @@ is available to
<div title="Hello {{ponyName}}"> + + <div title="Hello {{ponyName}}"> + +

Binds a property to an interpolated string, for example, "Hello Seabiscuit". Equivalent to: - <div [title]="'Hello ' + ponyName">

<p>Hello {{ponyName}}</p> + + <p>Hello {{ponyName}}</p> + +

Binds text content to an interpolated string, for example, "Hello Seabiscuit".

@@ -169,7 +226,11 @@ is available to
<my-cmp [(title)]="name"> + + <my-cmp [(title)]="name"> + +

Sets up two-way data binding. Equivalent to: <my-cmp [title]="name" (titleChange)="name=$event">

@@ -177,7 +238,11 @@ is available to
<video #movieplayer ...>
<button (click)="movieplayer.play()">
</video>
+ + <video #movieplayer ...>
<button (click)="movieplayer.play()">
</video>
+ +

Creates a local variable movieplayer that provides access to the video element instance in data-binding and event-binding expressions in the current template.

@@ -185,17 +250,24 @@ is available to
<p *myUnless="myExpression">...</p> + + <p *myUnless="myExpression">...</p> + +

The * symbol turns the current element into an embedded template. Equivalent to: - <ng-template [myUnless]="myExpression"><p>...</p></ng-template>

<p>Card No.: {{cardNumber | myCardNumberFormatter}}</p> + + <p>Card No.: {{cardNumber | myCardNumberFormatter}}</p> + +

Transforms the current value of expression cardNumber via the pipe called myCardNumberFormatter.

@@ -203,7 +275,11 @@ is available to
<p>Employer: {{employer?.companyName}}</p> + + <p>Employer: {{employer?.companyName}}</p> + +

The safe navigation operator (?) means that the employer field is optional and if undefined, the rest of the expression should be ignored.

@@ -211,7 +287,11 @@ is available to
<svg:rect x="0" y="0" width="100" height="100"/> + + <svg:rect x="0" y="0" width="100" height="100"/> + +

An SVG snippet template needs an svg: prefix on its root element to disambiguate the SVG element from an HTML component.

@@ -219,33 +299,41 @@ is available to
<svg>
<rect x="0" y="0" width="100" height="100"/>
</svg>
+ + <svg>
<rect x="0" y="0" width="100" height="100"/>
</svg>
+ +

An <svg> root element is detected as an SVG element automatically, without the prefix.

- - + - - + - + - + - + - - + -
Built-in directives + + Built-in directives + +

import { CommonModule } from '@angular/common'; -

<section *ngIf="showSection"> + + <section *ngIf="showSection"> + +

Removes or recreates a portion of the DOM tree based on the showSection expression.

@@ -253,7 +341,11 @@ is available to
<li *ngFor="let item of list"> + + <li *ngFor="let item of list"> + +

Turns the li element and its contents into a template, and uses that to instantiate a view for each item in list.

@@ -261,7 +353,11 @@ is available to
<div [ngSwitch]="conditionExpression">
<ng-template [ngSwitchCase]="case1Exp">...</ng-template>
<ng-template ngSwitchCase="case2LiteralString">...</ng-template>
<ng-template ngSwitchDefault>...</ng-template>
</div>
+ + <div [ngSwitch]="conditionExpression">
<ng-template [ngSwitchCase]="case1Exp">...</ng-template>
<ng-template ngSwitchCase="case2LiteralString">...</ng-template>
<ng-template ngSwitchDefault>...</ng-template>
</div>
+ +

Conditionally swaps the contents of the div by selecting one of the embedded templates based on the current value of conditionExpression.

@@ -269,69 +365,84 @@ is available to
<div [ngClass]="{'active': isActive, 'disabled': isDisabled}"> + + <div [ngClass]="{'active': isActive, 'disabled': isDisabled}"> + +

Binds the presence of CSS classes on the element to the truthiness of the associated map values. The right-hand expression should return {class-name: true/false} map.

<div [ngStyle]="{'property': 'value'}">
<div [ngStyle]="dynamicStyles()">
+ + <div [ngStyle]="{'property': 'value'}">
<div [ngStyle]="dynamicStyles()"> + +

Allows you to assign styles to an HTML element using CSS. You can use CSS directly, as in the first example, or you can call a method from the component.

- - + - - + -
Forms + + Forms + +

import { FormsModule } from '@angular/forms'; -

<input [(ngModel)]="userName"> + + <input [(ngModel)]="userName"> + +

Provides two-way data-binding, parsing, and validation for form controls.

- - + - - + - + - + - + -
Class decorators + + Class decorators + +

import { Directive, ... } from '@angular/core'; -

@Component({...})
class MyComponent() {}
+ + @Component({...})
class MyComponent() {}
+ +

Declares that a class is a component and provides metadata about the component.

@@ -339,7 +450,11 @@ is available to
@Directive({...})
class MyDirective() {}
+ + @Directive({...})
class MyDirective() {}
+ +

Declares that a class is a directive and provides metadata about the directive.

@@ -347,7 +462,11 @@ is available to
@Pipe({...})
class MyPipe() {}
+ + @Pipe({...})
class MyPipe() {}
+ +

Declares that a class is a pipe and provides metadata about the pipe.

@@ -355,76 +474,92 @@ is available to
@Injectable()
class MyService() {}
+ + @Injectable()
class MyService() {}
+ +

Declares that a class has dependencies that should be injected into the constructor when the dependency injector is creating an instance of this class. -

- - + - - + - + -
Directive configuration + + Directive configuration + +

@Directive({ property1: value1, ... }) -

selector: '.cool-button:not(a)' + + selector: '.cool-button:not(a)' + +

Specifies a CSS selector that identifies this directive within a template. Supported selectors include element, - [attribute], .class, and :not().

-

Does not support parent-child relationship selectors.

+

+ +Does not support parent-child relationship selectors. + +

providers: [MyService, { provide: ... }] + + providers: [MyService, { provide: ... }] + +

List of dependency injection providers for this directive and its children.

- - + - - + - + - + - + -
Component configuration + + Component configuration + +

- @Component extends @Directive, -so the - - @Directive configuration applies to components as well

+so the @Directive configuration applies to components as well

moduleId: module.id + + moduleId: module.id + +

If set, the templateUrl and styleUrl are resolved relative to the component.

@@ -432,7 +567,11 @@ so the
viewProviders: [MyService, { provide: ... }] + + viewProviders: [MyService, { provide: ... }] + +

List of dependency injection providers scoped to this component's view.

@@ -440,7 +579,11 @@ so the
template: 'Hello {{name}}'
templateUrl: 'my-component.html'
+ + template: 'Hello {{name}}'
templateUrl: 'my-component.html'
+ +

Inline template or external template URL of the component's view.

@@ -448,43 +591,54 @@ so the
styles: ['.primary {color: red}']
styleUrls: ['my-component.css']
+ + styles: ['.primary {color: red}']
styleUrls: ['my-component.css']
+ +

List of inline CSS styles or external stylesheet URLs for styling the component’s view.

- - + - - + - + - + - + - + - + - + - + -
Class field decorators for directives and components + + Class field decorators for directives and components + +

import { Input, ... } from '@angular/core'; -

@Input() myProperty; + + @Input() myProperty; + +

Declares an input property that you can update via property binding (example: - <my-cmp [myProperty]="someExpression">).

@Output() myEvent = new EventEmitter(); + + @Output() myEvent = new EventEmitter(); + +

Declares an output property that fires events that you can subscribe to with an event binding (example: <my-cmp (myEvent)="doSomething()">).

@@ -492,7 +646,11 @@ so the
@HostBinding('class.valid') isValid; + + @HostBinding('class.valid') isValid; + +

Binds a host element property (here, the CSS class valid) to a directive/component property (isValid).

@@ -500,7 +658,11 @@ so the
@HostListener('click', ['$event']) onClick(e) {...} + + @HostListener('click', ['$event']) onClick(e) {...} + +

Subscribes to a host element event (click) with a directive/component method (onClick), optionally passing an argument ($event).

@@ -508,7 +670,11 @@ so the
@ContentChild(myPredicate) myChildComponent; + + @ContentChild(myPredicate) myChildComponent; + +

Binds the first result of the component content query (myPredicate) to a property (myChildComponent) of the class.

@@ -516,7 +682,11 @@ so the
@ContentChildren(myPredicate) myChildComponents; + + @ContentChildren(myPredicate) myChildComponents; + +

Binds the results of the component content query (myPredicate) to a property (myChildComponents) of the class.

@@ -524,7 +694,11 @@ so the
@ViewChild(myPredicate) myChildComponent; + + @ViewChild(myPredicate) myChildComponent; + +

Binds the first result of the component view query (myPredicate) to a property (myChildComponent) of the class. Not available for directives.

@@ -532,33 +706,41 @@ so the
@ViewChildren(myPredicate) myChildComponents; + + @ViewChildren(myPredicate) myChildComponents; + +

Binds the results of the component view query (myPredicate) to a property (myChildComponents) of the class. Not available for directives.

- - + - - + - + - + - + - + - + - + - + - + -
Directive and component change detection and lifecycle hooks + + Directive and component change detection and lifecycle hooks + +

(implemented as class methods) -

constructor(myService: MyService, ...) { ... } + + constructor(myService: MyService, ...) { ... } + +

Called before any other lifecycle hook. Use it to inject dependencies, but avoid any serious work here.

@@ -566,7 +748,11 @@ so the
ngOnChanges(changeRecord) { ... } + + ngOnChanges(changeRecord) { ... } + +

Called after every change to input properties and before processing content or child views.

@@ -574,7 +760,11 @@ so the
ngOnInit() { ... } + + ngOnInit() { ... } + +

Called after the constructor, initializing input properties, and the first call to ngOnChanges.

@@ -582,7 +772,11 @@ so the
ngDoCheck() { ... } + + ngDoCheck() { ... } + +

Called every time that the input properties of a component or a directive are checked. Use it to extend change detection by performing a custom check.

@@ -590,7 +784,11 @@ so the
ngAfterContentInit() { ... } + + ngAfterContentInit() { ... } + +

Called after ngOnInit when the component's or directive's content has been initialized.

@@ -598,7 +796,11 @@ so the
ngAfterContentChecked() { ... } + + ngAfterContentChecked() { ... } + +

Called after every check of the component's or directive's content.

@@ -606,7 +808,11 @@ so the
ngAfterViewInit() { ... } + + ngAfterViewInit() { ... } + +

Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.

@@ -614,7 +820,11 @@ so the
ngAfterViewChecked() { ... } + + ngAfterViewChecked() { ... } + +

Called after every check of the component's view. Applies to components only.

@@ -622,29 +832,40 @@ so the
ngOnDestroy() { ... } + + ngOnDestroy() { ... } + +

Called once, before the instance is destroyed.

- - + + Dependency injection configuration + + + + - - + - + - + -
Dependency injection configuration - + +
{ provide: MyService, useClass: MyMockService } + + { provide: MyService, useClass: MyMockService } + +

Sets or overrides the provider for MyService to the MyMockService class.

@@ -652,7 +873,11 @@ so the
{ provide: MyService, useFactory: myFactory } + + { provide: MyService, useFactory: myFactory } + +

Sets or overrides the provider for MyService to the myFactory factory function.

@@ -660,33 +885,41 @@ so the
{ provide: MyValue, useValue: 41 } + + { provide: MyValue, useValue: 41 } + +

Sets or overrides the provider for MyValue to the value 41.

- - + - - + - + - + - + - + - + - + - + - + -
Routing and navigation + + Routing and navigation + +

import { Routes, RouterModule, ... } from '@angular/router'; -

const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'path/:routeParam', component: MyComponent },
{ path: 'staticPath', component: ... },
{ path: '**', component: ... },
{ path: 'oldPath', redirectTo: '/staticPath' },
{ path: ..., component: ..., data: { message: 'Custom' } }
]);

const routing = RouterModule.forRoot(routes);
+ + const routes: Routes = [
{ path: '', component: HomeComponent },
{ path: 'path/:routeParam', component: MyComponent },
{ path: 'staticPath', component: ... },
{ path: '**', component: ... },
{ path: 'oldPath', redirectTo: '/staticPath' },
{ path: ..., component: ..., data: { message: 'Custom' } }
]);

const routing = RouterModule.forRoot(routes);
+ +

Configures routes for the application. Supports static, parameterized, redirect, and wildcard routes. Also supports custom route data and resolve.

@@ -694,7 +927,11 @@ so the

<router-outlet></router-outlet>
<router-outlet name="aux"></router-outlet>
+ +
<router-outlet></router-outlet>
<router-outlet name="aux"></router-outlet>
+ +

Marks the location to load the component of the active route.

@@ -702,7 +939,11 @@ so the

<a routerLink="/path">
<a [routerLink]="[ '/path', routeParam ]">
<a [routerLink]="[ '/path', { matrixParam: 'value' } ]">
<a [routerLink]="[ '/path' ]" [queryParams]="{ page: 1 }">
<a [routerLink]="[ '/path' ]" fragment="anchor">
+ +
<a routerLink="/path">
<a [routerLink]="[ '/path', routeParam ]">
<a [routerLink]="[ '/path', { matrixParam: 'value' } ]">
<a [routerLink]="[ '/path' ]" [queryParams]="{ page: 1 }">
<a [routerLink]="[ '/path' ]" fragment="anchor">
+ +

Creates a link to a different view based on a route instruction consisting of a route path, required and optional parameters, query parameters, and a fragment. To navigate to a root route, use the / prefix; for a child route, use the ./prefix; for a sibling or parent, use the ../ prefix.

@@ -710,7 +951,11 @@ so the
<a [routerLink]="[ '/path' ]" routerLinkActive="active"> + + <a [routerLink]="[ '/path' ]" routerLinkActive="active"> + +

The provided classes are added to the element when the routerLink becomes the current active route.

@@ -718,7 +963,11 @@ so the
class CanActivateGuard implements CanActivate {
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean { ... }
}

{ path: ..., canActivate: [CanActivateGuard] }
+ + class CanActivateGuard implements CanActivate {
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean { ... }
}

{ path: ..., canActivate: [CanActivateGuard] }
+ +

An interface for defining a class that the router should call first to determine if it should activate this component. Should return a boolean or an Observable/Promise that resolves to a boolean.

@@ -726,7 +975,11 @@ so the
class CanDeactivateGuard implements CanDeactivate<T> {
canDeactivate(
component: T,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean { ... }
}

{ path: ..., canDeactivate: [CanDeactivateGuard] }
+ + class CanDeactivateGuard implements CanDeactivate<T> {
canDeactivate(
component: T,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean { ... }
}

{ path: ..., canDeactivate: [CanDeactivateGuard] }
+ +

An interface for defining a class that the router should call first to determine if it should deactivate this component after a navigation. Should return a boolean or an Observable/Promise that resolves to a boolean.

@@ -734,7 +987,11 @@ so the
class CanActivateChildGuard implements CanActivateChild {
canActivateChild(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean { ... }
}

{ path: ..., canActivateChild: [CanActivateGuard],
children: ... }
+ + class CanActivateChildGuard implements CanActivateChild {
canActivateChild(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean>|Promise<boolean>|boolean { ... }
}

{ path: ..., canActivateChild: [CanActivateGuard],
children: ... }
+ +

An interface for defining a class that the router should call first to determine if it should activate the child route. Should return a boolean or an Observable/Promise that resolves to a boolean.

@@ -742,7 +999,11 @@ so the
class ResolveGuard implements Resolve<T> {
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any>|Promise<any>|any { ... }
}

{ path: ..., resolve: [ResolveGuard] }
+ + class ResolveGuard implements Resolve<T> {
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any>|Promise<any>|any { ... }
}

{ path: ..., resolve: [ResolveGuard] }
+ +

An interface for defining a class that the router should call first to resolve route data before rendering the route. Should return a value or an Observable/Promise that resolves to a value.

@@ -750,15 +1011,17 @@ so the
class CanLoadGuard implements CanLoad {
canLoad(
route: Route
): Observable<boolean>|Promise<boolean>|boolean { ... }
}

{ path: ..., canLoad: [CanLoadGuard], loadChildren: ... }
+ + class CanLoadGuard implements CanLoad {
canLoad(
route: Route
): Observable<boolean>|Promise<boolean>|boolean { ... }
}

{ path: ..., canLoad: [CanLoadGuard], loadChildren: ... }
+ +

An interface for defining a class that the router should call first to check if the lazy loaded module should be loaded. Should return a boolean or an Observable/Promise that resolves to a boolean.

- diff --git a/aio/content/guide/comparing-observables.md b/aio/content/guide/comparing-observables.md index 2587f67cb7..cd6f1a32c2 100644 --- a/aio/content/guide/comparing-observables.md +++ b/aio/content/guide/comparing-observables.md @@ -97,25 +97,39 @@ The following code snippets illustrate how the same kind of operation is defined - Operation + - Observable + Operation - Promise + + + + + Observable + + + + + + Promise + + - Creation + + + Creation + +
new Observable((observer) => {
   observer.next(123);
-});
-
-
+});
@@ -123,35 +137,45 @@ The following code snippets illustrate how the same kind of operation is defined
new Promise((resolve, reject) => {
   resolve(123);
-});
-
-
+});
- - Transform + -
obs.map((value) => value * 2 );
+ Transform -
promise.then((value) => value * 2);
+ + + + +
obs.map((value) => value * 2 );
+ + + + + +
promise.then((value) => value * 2);
+ + - - Subscribe + + + Subscribe + +
sub = obs.subscribe((value) => {
   console.log(value)
-});
-
-
+});
@@ -159,24 +183,32 @@ The following code snippets illustrate how the same kind of operation is defined
promise.then((value) => {
   console.log(value);
-});
-
-
+});
- - Unsubscribe + -
sub.unsubscribe();
+ Unsubscribe - Implied by promise resolution. + + + + +
sub.unsubscribe();
+ + + + + + Implied by promise resolution. + + - ## Observables compared to events API @@ -191,15 +223,27 @@ Here are some code samples that illustrate how the same kind of operation is def - Observable + - Events API + Observable + + + + + + Events API + + - Creation & cancellation + + + Creation & cancellation + + @@ -209,9 +253,7 @@ let clicks$ = fromEvent(buttonEl, ‘click’); let subscription = clicks$ .subscribe(e => console.log(‘Clicked’, e)) // Stop listening -subscription.unsubscribe(); - - +subscription.unsubscribe(); @@ -225,24 +267,24 @@ subscription.unsubscribe(); button.addEventListener(‘click’, handler); // Stop listening button.removeEventListener(‘click’, handler); - - - Subscription + + + Subscription + +
observable.subscribe(() => {
   // notification handlers here
-});
-
-
+}); @@ -250,24 +292,23 @@ button.removeEventListener(‘click’, handler);
element.addEventListener(eventName, (event) => {
   // notification handler here
-});
-
-
+}); - - Configuration + + + Configuration + + Listen for keystrokes, but provide a stream representing the value in the input.
fromEvent(inputEl, 'keydown').pipe(
   map(e => e.target.value)
-);
-
-
+); @@ -275,14 +316,11 @@ button.removeEventListener(‘click’, handler);
element.addEventListener(eventName, (event) => {
   // Cannot change the passed Event into another
   // value before it gets to the handler
-});
-
-
+}); - ## Observables compared to arrays @@ -293,20 +331,31 @@ An observable produces values over time. An array is created as a static set of - Observable + - Array + Observable + + + + + + Array + + - Given + + + Given + +
obs: ➞1➞2➞3➞5➞7
-
obsB: ➞'a'➞'b'➞'c'
@@ -314,21 +363,22 @@ An observable produces values over time. An array is created as a static set of
arr: [1, 2, 3, 5, 7]
-
arrB: ['a', 'b', 'c']
- -
concat()
+ + +
concat()
+ +
obs.concat(obsB)
-
➞1➞2➞3➞5➞7➞'a'➞'b'➞'c'
@@ -336,21 +386,22 @@ An observable produces values over time. An array is created as a static set of
arr.concat(arrB)
-
[1,2,3,5,7,'a','b','c']
- -
filter()
+ + +
filter()
+ +
obs.filter((v) => v>3)
-
➞5➞7
@@ -358,21 +409,22 @@ An observable produces values over time. An array is created as a static set of
arr.filter((v) => v>3)
-
[5, 7]
- -
find()
+ + +
find()
+ +
obs.find((v) => v>3)
-
➞5
@@ -380,21 +432,22 @@ An observable produces values over time. An array is created as a static set of
arr.find((v) => v>10)
-
5
- -
findIndex()
+ + +
findIndex()
+ +
obs.findIndex((v) => v>3)
-
➞3
@@ -402,16 +455,18 @@ An observable produces values over time. An array is created as a static set of
arr.findIndex((v) => v>3)
-
3
- -
forEach()
+ + +
forEach()
+ + @@ -422,9 +477,7 @@ An observable produces values over time. An array is created as a static set of 2 3 4 -5 - - +5 @@ -437,22 +490,22 @@ An observable produces values over time. An array is created as a static set of 2 3 4 -5 - - +5 - -
map()
+ + +
map()
+ +
obs.map((v) => -v)
-
➞-1➞-2➞-3➞-5➞-7
@@ -460,21 +513,22 @@ An observable produces values over time. An array is created as a static set of
arr.map((v) => -v)
-
[-1, -2, -3, -5, -7]
- -
reduce()
+ + +
reduce()
+ +
obs.scan((s,v)=> s+v, 0)
-
➞1➞3➞6➞11➞18
@@ -482,12 +536,9 @@ An observable produces values over time. An array is created as a static set of
arr.reduce((s,v) => s+v, 0)
-
18
- - diff --git a/aio/content/guide/component-interaction.md b/aio/content/guide/component-interaction.md index 1c5aeee5a6..a1e1d1bd8f 100644 --- a/aio/content/guide/component-interaction.md +++ b/aio/content/guide/component-interaction.md @@ -77,13 +77,13 @@ The running application displays three heroes: 运行应用程序会显示三个英雄:
- Parent-to-child -

Test it

+

测试一下

+ E2E test that all children were instantiated and displayed as expected: 端到端测试,用于确保所有的子组件都像所期待的那样被初始化并显示出来。 @@ -124,13 +124,13 @@ Here's the `NameParentComponent` demonstrating name variations including a name
- Parent-to-child-setter -

Test it

+

测试一下

+ E2E tests of input property setter with empty and non-empty names: 端到端测试:输入属性的setter,分别使用空名字和非空名字。 @@ -186,9 +186,7 @@ Here's the output of a button-pushing sequence: 下面是点击按钮的结果。
- Parent-to-child-onchanges -

Test it

@@ -248,9 +246,7 @@ and the method processes it: 框架(Angular)把事件参数(用`$event`表示)传给事件处理方法,这个方法会处理:
- Child-to-parent -

Test it

@@ -282,6 +278,7 @@ as seen in the following example. 父组件不能使用数据绑定来读取子组件的属性或调用子组件的方法。但可以在父组件模板里,新建一个本地变量来代表子组件,然后利用这个变量来读取子组件的属性和调用子组件的方法,如下例所示。 {@a countdown-timer-example} + The following is a child `CountdownTimerComponent` that repeatedly counts down to zero and launches a rocket. It has `start` and `stop` methods that control the clock and it displays a countdown status message in its own template. @@ -321,9 +318,7 @@ Here we see the parent and child working together. 下面是父组件和子组件一起工作时的效果。
- countdown timer -
{@a countdown-tests} @@ -512,9 +507,7 @@ facilitated by the service: *History*日志证明了:在父组件`MissionControlComponent`和子组件`AstronautComponent`之间,信息通过该服务实现了双向传递。
- bidirectional-service -

Test it

@@ -533,4 +526,4 @@ and verify that the history meets expectations: [Back to top](guide/component-interaction#top) -[回到顶部](guide/component-interaction#top) \ No newline at end of file +[回到顶部](guide/component-interaction#top) diff --git a/aio/content/guide/component-styles.md b/aio/content/guide/component-styles.md index d70055fab6..7982777e93 100644 --- a/aio/content/guide/component-styles.md +++ b/aio/content/guide/component-styles.md @@ -20,7 +20,7 @@ This page describes how to load and apply these component styles. You can run the in Stackblitz and download the code from there. -你可以在 Stackblitz 上运行本章这些代码的并下载这些代码。 +运行来试用本页的代码。 ## Using component styles @@ -290,11 +290,8 @@ to a component's `@Component` decorator: 我们可以通过把外部 CSS 文件添加到 `@Component` 的 `styleUrls` 属性中来加载外部样式。 - - -
@@ -541,4 +538,4 @@ These extra selectors enable the scoping rules described in this page. 这些就是我们写的那些样式被处理后的结果,于是每个选择器都被增加了`_nghost`或`_ngcontent`属性选择器。 -在这些附加选择器的帮助下,我们实现了本指南中所描述的这些作用域规则。 \ No newline at end of file +在这些附加选择器的帮助下,我们实现了本指南中所描述的这些作用域规则。 diff --git a/aio/content/guide/dependency-injection-in-action.md b/aio/content/guide/dependency-injection-in-action.md index 6d7047d570..df03b4e0c3 100644 --- a/aio/content/guide/dependency-injection-in-action.md +++ b/aio/content/guide/dependency-injection-in-action.md @@ -9,7 +9,8 @@ This cookbook explores many of the features of Dependency Injection (DI) in Angu {@a toc} -See the of the code in this cookbook. +See the +of the code in this cookbook. 到查看本烹饪书的源码。 @@ -150,9 +151,7 @@ Once all the dependencies are in place, the `AppComponent` displays the user inf 一旦所有依赖都准备好了,`AppComponent`就会显示用户信息:
- Logged In User -
{@a injectable-1} @@ -307,6 +306,7 @@ This is called *sandboxing* because each service and component instance has its 每个服务有自己的工作状态,与其它组件的服务和状态隔离。我们称作*沙盒化*,因为每个服务和组件实例都在自己的沙盒里运行。 {@a hero-bios-component} + Imagine a `HeroBiosComponent` that presents three instances of the `HeroBioComponent`. 想象一下,一个`HeroBiosComponent`组件显示三个`HeroBioComponent`的实例。 @@ -345,14 +345,13 @@ And the template displays this data-bound property. 父组件`HeroBiosComponent`把一个值绑定到`heroId`。`ngOnInit`把该`id`传递到服务,然后服务获取和缓存英雄。`hero`属性的getter从服务里面获取缓存的英雄,并在模板里显示它绑定到属性值。 -Find this example in live code and confirm that the three `HeroBioComponent` instances have their own cached hero data. +Find this example in live code +and confirm that the three `HeroBioComponent` instances have their own cached hero data. 到在线例子中找到这个例子,确认三个`HeroBioComponent`实例拥有自己独立的英雄数据缓存。
- Bios -
{@a optional} @@ -435,9 +434,7 @@ It looks like this, with the hero's telephone number from `HeroContactComponent` 从`HeroContactComponent`获得的英雄电话号码,被投影到上面的英雄描述里,就像这样:
- bio and contact -
Here's the `HeroContactComponent` which demonstrates the qualifying decorators: @@ -480,9 +477,7 @@ Here's the `HeroBiosAndContactsComponent` in action. 下面是`HeroBiosAndContactsComponent`的执行结果:
- Bios with contact into -
If you comment out the `@Host()` decorator, Angular now walks up the injector ancestor tree @@ -492,9 +487,7 @@ with the gratuitous "!!!", indicating that the logger was found. 如果注释掉`@Host()`装饰器,Angular就会沿着注入器树往上走,直到在`AppComponent`中找到该日志服务。日志服务的逻辑加入进来,更新了英雄的显示信息,这表明确实找到了日志服务。
- Without @Host -
On the other hand, if you restore the `@Host()` decorator and comment out `@Optional`, @@ -552,9 +545,7 @@ The following image shows the effect of mousing over the ``标签的效果:
- Highlighted bios -
{@a providers} @@ -650,9 +641,7 @@ It's visually simple: a few properties and the logs produced by a logger. 它看起来很简单:一些属性和一个日志输出。
- Hero of the month -
The code behind it gives you plenty to think about. @@ -831,9 +820,7 @@ The `HeroOfTheMonthComponent` constructor's `logger` parameter is typed as `Mini `HeroOfTheMonthComponent`构造函数的`logger`参数是一个`MinimalLogger`类型,支持TypeScript的编辑器里,只能看到它的两个成员`logs`和`logInfo`:
- MinimalLogger restricted API -
Behind the scenes, Angular actually sets the `logger` parameter to the full service registered under the `LoggingService` token which happens to be the `DateLoggerService` that was [provided above](guide/dependency-injection-in-action#useclass). @@ -848,9 +835,7 @@ The following image, which displays the logging date, confirms the point: 在下面的图片中,显示了日志日期,可以确认这一点:
- DateLoggerService entry -
@@ -1087,9 +1072,7 @@ to display a *sorted* list of heroes. 在这个刻意生成的例子里,`SortedHeroesComponent`继承自`HeroesBaseComponent`,显示一个*被排序*的英雄列表。
- Sorted Heroes -
The `HeroesBaseComponent` could stand on its own. @@ -1266,7 +1249,6 @@ you see that the `Alex` component *extends* (*inherits*) from a class named `Bas `CraigComponent`例子探究了这个问题。[往回看Alex]{guide/dependency-injection-in-action#alex},我们看到`Alex`组件*扩展*(*派生*)自一个叫`Base`的类。 - @@ -1338,9 +1320,7 @@ Here's *Alex* and family in action: 下面是*Alex*和其家庭的运行结果:
- Alex in action -
{@a parent-tree} @@ -1416,9 +1396,7 @@ Here's *Alice*, *Barry* and family in action: 这里是*Alice*,*Barry*和该家庭的操作演示:
- Alice in action -
{@a parent-token} @@ -1567,4 +1545,3 @@ Break the circularity with `forwardRef`: - diff --git a/aio/content/guide/dependency-injection-pattern.md b/aio/content/guide/dependency-injection-pattern.md index dad2fc6877..805592e8fd 100644 --- a/aio/content/guide/dependency-injection-pattern.md +++ b/aio/content/guide/dependency-injection-pattern.md @@ -65,16 +65,15 @@ When you can't control the dependencies, a class becomes difficult to test. How can you make `Car` more robust, flexible, and testable? {@a ctor-injection} + That's super easy. Change the `Car` constructor to a version with DI: - - diff --git a/aio/content/guide/dependency-injection.md b/aio/content/guide/dependency-injection.md index 3009e45bf6..f9963e41d1 100644 --- a/aio/content/guide/dependency-injection.md +++ b/aio/content/guide/dependency-injection.md @@ -16,22 +16,17 @@ Start by reviewing this simplified version of the _heroes_ feature from the [The Tour of Heroes](tutorial/). - - - - - @@ -88,6 +83,7 @@ That's a defect we can safely ignore in this guide where our focus is on _injecting the service_ into the `HeroList` component. {@a injector-config} + {@a bootstrap} ## Register a service provider @@ -199,7 +195,7 @@ providing the `HeroService` in the `HeroComponent` may be a good choice.
-The scope and lifetime of component-provided services is a consequence of [the way Angular creates component instances](#component-child-injectors). +The scope and lifetime of component-provided services is a consequence of [the way Angular creates component instances](#component-child-injectors).
@@ -222,15 +218,11 @@ Of course, the `HeroListComponent` should do something with the injected `HeroSe Here's the revised component, making use of the injected service, side-by-side with the previous version for comparison. - - - - Notice that the `HeroListComponent` doesn't know where the `HeroService` comes from. @@ -329,11 +321,9 @@ Here is the revised `HeroService` that injects the `Logger`, side-by-side with t - - @@ -734,11 +724,9 @@ Here you see the new and the old implementation side-by-side: - - @@ -1063,4 +1051,3 @@ But it's best to avoid the problem altogether by defining components and service 还是通过在独立的文件中定义组件和服务,完全避免此问题吧。
- diff --git a/aio/content/guide/deployment.md b/aio/content/guide/deployment.md index a41ac7b44f..9256d39749 100644 --- a/aio/content/guide/deployment.md +++ b/aio/content/guide/deployment.md @@ -7,6 +7,7 @@ This page describes techniques for deploying your Angular application to a remot 本章会描述在远程服务器上部署Angular应用的工具与技术。 {@a dev-deploy} + {@a copy-files} ## Simplest deployment possible @@ -33,7 +34,7 @@ For the simplest deployment, build for development and copy the output directory 3. If you copy the files into a server _sub-folder_, append the build flag, `--base-href` and set the `` appropriately.

- 如果要把文件部署到服务器上的*某个子路径*下,构建时还要添加`--base-href`(基地址)标识,并设置合适的``。

+ 如果要把文件部署到服务器上的*某个子路径*下,构建时还要添加`--base-href`(基地址)标识,并设置合适的``。

For example, if the `index.html` is on the server at `/my/app/index.html`, set the _base href_ to `` like this. @@ -256,9 +257,7 @@ showing exactly which classes are included in the bundle. Here's the output for the _main_ bundle of the QuickStart.
- quickstart sourcemap explorer -
{@a base-tag} @@ -524,4 +523,4 @@ Read about how to enable CORS for specific servers at 客户端应用对这种错误无能为力。 服务器必须配置成可以接受来自该应用的请求。 -要了解如何对特定的服务器开启CORS,参见enable-cors.org。 \ No newline at end of file +要了解如何对特定的服务器开启CORS,参见enable-cors.org。 diff --git a/aio/content/guide/displaying-data.md b/aio/content/guide/displaying-data.md index 3e2d632c2c..14836906b4 100644 --- a/aio/content/guide/displaying-data.md +++ b/aio/content/guide/displaying-data.md @@ -18,9 +18,7 @@ The final UI looks like this: 最终的用户界面是这样的:
- Final UI -
@@ -135,9 +133,7 @@ Now run the app. It should display the title and hero name: 运行应用。它应该显示出标题和英雄名:
- Title and Hero -
The next few sections review some of the coding choices in the app. @@ -275,9 +271,7 @@ Now the heroes appear in an unordered list. 现在,英雄们出现在了一个无序列表中。
- After ngfor -
## Creating a class for the data @@ -337,15 +331,15 @@ That brief syntax does a lot: * Declares a constructor parameter and its type. - 声明了一个构造函数参数及其类型。 + 声明了一个构造函数参数及其类型。 * Declares a public property of the same name. - 声明了一个同名的公共属性。 + 声明了一个同名的公共属性。 * Initializes that property with the corresponding argument when creating an instance of the class. - 当我们`new`出该类的一个实例时,把该属性初始化为相应的参数值。 + 当我们`new`出该类的一个实例时,把该属性初始化为相应的参数值。 ### Using the Hero class @@ -487,4 +481,3 @@ Here's the final code: - diff --git a/aio/content/guide/docs-style-guide.md b/aio/content/guide/docs-style-guide.md index e39838f598..cd0ccf8375 100644 --- a/aio/content/guide/docs-style-guide.md +++ b/aio/content/guide/docs-style-guide.md @@ -12,7 +12,9 @@ For clarity and precision, every guideline on _this_ page is illustrated with a followed by the page markup for that example ... as shown here. ```html + followed by the page markup for that example ... as shown here. + ``` ## Doc generation and tooling @@ -123,11 +125,8 @@ All section heading text should be in "Sentence case", which means the first wor **Always follow the section heading with at least one blank line.**

- Main section heading -

- There are usually one or more main sections that may be further divided into secondary sections. Begin a main section heading with the markdown `##` characters. Alternatively, you can write the equivalent `

` HTML tag. @@ -139,12 +138,11 @@ The main section heading should be followed by a blank line and then the content ## Sections A typical document is divided into sections. + ```

- Secondary section heading -

A secondary section heading is related to a main heading and _falls textually within_ the bounds of that main heading. @@ -158,6 +156,7 @@ The secondary heading should be followed by a blank line and then the content fo ### Secondary section heading A secondary section ... + ``` #### Additional section headings @@ -171,6 +170,7 @@ Try to minimize the heading depth, preferably only two. But more headings, such #### Additional section headings Try to minimize ... + ``` ## Subsections @@ -214,9 +214,7 @@ To exclude a heading from the TOC, create the heading as an `

` or `

` ele ```html

- This heading is not displayed in the TOC -

``` @@ -226,9 +224,7 @@ You can turn off TOC generation for the _entire_ page by writing the title with ```html

- A guide without a TOC -

``` @@ -247,11 +243,13 @@ Look for the `SideNav` node in `navigation.json`. The `SideNav` node is an array Find the header for your page. For example, a guide page that describes an Angular feature is probably a child of the `Fundamentals` header. ```html + { "title": "Fundamentals", "tooltip": "The fundamentals of Angular", "children": [ ... ] } + ``` A _header_ node child can be an _item_ node or another _header_ node. If your guide page belongs under a sub-header, find that sub-header in the JSON. @@ -259,11 +257,13 @@ A _header_ node child can be an _item_ node or another _header_ node. If your gu Add an _item_ node for your guide page as a child of the appropriate _header_ node. It probably looks something like this one. ```html + { "url": "guide/architecture", "title": "Architecture", "tooltip": "The basic building blocks of Angular applications." } + ``` A navigation node has the following properties: @@ -368,6 +368,7 @@ The following _code-example_ displays the sample's `app.module.ts`. Here's the brief markup that produced that lengthy snippet: ```html + @@ -443,6 +444,7 @@ First you surround that fragment in the source file with a named _docregion_ as Then you reference that _docregion_ in the `region` attribute of the `` like this ```html + @@ -472,6 +474,7 @@ Here's the markup for an "avoid" example in the [_Angular Style Guide_](guide/styleguide#style-05-03 "Style 05-03: components as elements"). ```html + ` and `` levels. - - - - - - - - - Here's the markup for that example. @@ -544,33 +538,24 @@ The `linenums` attribute in the second pane restores line numbering for _itself ```html - - - - - - - - - ``` @@ -590,22 +575,31 @@ The sample source code for this page, located in `context/examples/docs-style-gu Code snippet markup is always in the form of a comment. Here's the default _docregion_ markup for a TypeScript or JavaScript file: ``` + // #docregion ... some code ... // #enddocregion + ``` + Different file types have different comment syntax so adjust accordingly. ```html + + ... some HTML ... + + ``` ``` + /* #docregion */ ... some CSS ... /* #enddocregion */ + ``` The doc generation process erases these comments before displaying them in the doc viewer. @@ -633,9 +627,7 @@ The `src/main.ts` is a simple example of a file with a single _#docregion_ at th - - + title="src/main.ts">
@@ -645,19 +637,20 @@ You'll often display multiple snippets from different fragments within the same You distinguish among them by giving each fragment its own _#docregion name_ as follows. ``` + // #docregion region-name ... some code ... // #enddocregion region-name + ``` Remember to refer to this region by name in the `region` attribute of the `` or `` as you did in an example above like this: ```html + - - + region="class"> ``` @@ -666,7 +659,9 @@ The _#docregion_ with no name is the _default region_. Do _not_ set the `region` #### Nested _#docregions_ You can nest _#docregions_ within _#docregions_ + ``` + // #docregion ... some code ... // #docregion inner-region @@ -674,6 +669,7 @@ You can nest _#docregions_ within _#docregions_ // #enddocregion inner-region ... yet more code ... /// #enddocregion + ```
@@ -714,21 +710,16 @@ export class AppComponent { Here's are the two corresponding code snippets displayed side-by-side. - - - - - Some observations: @@ -758,16 +749,13 @@ Here's an example that excerpts certain scripts from `package.json` into a parti - - + title="package.json (selected scripts)"> ```html + - - + title="package.json (selected scripts)"> ``` @@ -781,9 +769,11 @@ Such partial and intermediate files need their own names. Follow the doc sample naming convention. Add a number before the file extension as illustrated here: ```html + package.1.json app.component.1.ts app.component.2.ts + ``` You'll find many such files among the samples in the Angular documentation. @@ -792,9 +782,7 @@ Remember to exclude these files from stackblitz by listing them in the `stackbli - - + title="stackblitz.json"> {@a live-examples} @@ -939,7 +927,9 @@ See the ["Anchors"](guide/docs-style-guide#anchors "Style Guide - Anchors") sect When navigating within the page, you can omit the page URL when specifying the link that [scrolls up](#anchors "Anchors") to the beginning of this section. ```html + ... the link that [scrolls up](#anchors "Anchors") to ... + ``` {@a ugly-anchors} @@ -951,7 +941,9 @@ It is often a good idea to *lock-in* a good anchor name. Sometimes the section header text makes for an unattractive anchor. [This one](#ugly-long-section-header-anchors) is pretty bad. ```html + [This one](#ugly-long-section-header-anchors) is pretty bad. + ``` The greater danger is that **a future rewording of the header text would break** a link to this section. @@ -970,7 +962,9 @@ text to which it applies, using the special `{@a name}` syntax like this. Now [link to that custom anchor name](#ugly-anchors) as you did before. ```html + Now [link to that custom anchor name](#ugly-anchors) as you did before. + ```
@@ -980,6 +974,7 @@ Alternatively, you can use the HTML `` tag. If you do, be sure to set the `id` attribute - not the `name` attribute! The docs generator will not convert the `name` to the proper link URL. ```html + ## Anchors @@ -1011,6 +1006,7 @@ A helpful, informational alert.
Here is the markup for these alerts. + ```html
@@ -1042,7 +1038,11 @@ Callouts (like alerts) are meant to draw attention to important points. Use a ca
-
A critical point
+
+ +A critical point + +
**Pitchfork hoodie semiotics**, roof party pop-up _paleo_ messenger messenger bag cred Carles tousled Truffaut yr. Semiotics viral freegan VHS, Shoreditch disrupt McSweeney's. Intelligentsia kale chips Vice four dollar toast, Schlitz crucifix @@ -1050,7 +1050,11 @@ Callouts (like alerts) are meant to draw attention to important points. Use a ca
-
An important point
+
+ +An important point + +
**Pitchfork hoodie semiotics**, roof party pop-up _paleo_ messenger bag cred Carles tousled Truffaut yr. Semiotics viral freegan VHS, Shoreditch disrupt McSweeney's. Intelligentsia kale chips Vice four dollar toast, Schlitz crucifix @@ -1058,18 +1062,27 @@ Callouts (like alerts) are meant to draw attention to important points. Use a ca
-
A helpful point
+
+ +A helpful point + +
**Pitchfork hoodie semiotics**, roof party pop-up _paleo_ messenger bag cred Carles tousled Truffaut yr. Semiotics viral freegan VHS, Shoreditch disrupt McSweeney's. Intelligentsia kale chips Vice four dollar toast, Schlitz crucifix
Here is the markup for the first of these callouts. + ```html
-
A critical point
+
+ +A critical point + +
**Pitchfork hoodie semiotics**, roof party pop-up _paleo_ messenger bag cred Carles tousled Truffaut yr. Semiotics viral freegan VHS, Shoreditch disrupt McSweeney's. Intelligentsia kale chips Vice four dollar toast, Schlitz crucifix @@ -1242,38 +1255,65 @@ Here is the markup for this file tree. Use HTML tables to present tabular data. - - + + Framework - + + + + + - - + + AngularJS - + + + + + - - + + Angular v2 + + + + @@ -1284,12 +1324,19 @@ Use HTML tables to present tabular data. - - + + Angular v4 + + + + -
Framework - TaskSpeed + + Task + + + + Speed + +
AngularJS - RoutingFast + + Routing + + + + Fast + +
Angular v2 - Routing + + Routing + +
Angular v4 - Routing + + Routing + + @@ -1298,7 +1345,6 @@ Use HTML tables to present tabular data.
Here is the markup for this table. @@ -1306,38 +1352,65 @@ Here is the markup for this table. ```html - - + + Framework - + + + + + - - + + AngularJS - + + + + + - - + + Angular v2 + + + + @@ -1348,12 +1421,19 @@ Here is the markup for this table. - - + + Angular v4 + + + + -
Framework - TaskSpeed + + Task + + + + Speed + +
AngularJS - RoutingFast + + Routing + + + + Fast + +
Angular v2 - Routing + + Routing + +
Angular v4 - Routing + + Routing + + @@ -1362,7 +1442,6 @@ Here is the markup for this table.
``` @@ -1378,8 +1457,11 @@ Angular doc generation copies these image folders to the _runtime_ location, `ge Set the image `src` attribute to begin in _that_ directory. Here's the `src` attribute for the "flying hero" image belonging to this page. + ``` + src="generated/images/guide/docs-style-guide/flying-hero.png" + ```

Use the HTML <img> tag

@@ -1395,18 +1477,14 @@ You should nest the `` tag within a `
` tag, which styles the image Here's a conforming example
- flying hero -
```html
- flying hero -
``` @@ -1420,19 +1498,15 @@ The doc generator reads the image dimensions from the file and adds width and he Here's the "flying hero" at a more reasonable scale.
- flying Angular hero -
```html
- flying Angular hero -
``` @@ -1442,13 +1516,9 @@ Wide images can be a problem. Most browsers try to rescale the image but wide im **Do not set a width greater than 700px**. If you wish to display a larger image, provide a link to the actual image that the user can click on to see the full size image separately as in this example of `source-map-explorer` output from the "Ahead-of-time Compilation" guide: -
- toh-pt6-bundle -
-

Image compression

@@ -1474,6 +1544,7 @@ Headings and code-examples automatically clear a floating image. If you need to The markup for the above example is: ```html +