Cheat Sheet

速查表

Bootstrapping 引导/启动

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

platformBrowserDynamic().bootstrapModule(AppModule);

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

NgModule 中指定的根组件进行启动。

NgModules

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

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

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

定义一个模块,其中可以包含组件、指令、管道和服务提供商。

declarations: [MyRedComponent, MyBlueComponent, MyDatePipe]

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

属于当前模块的组件、指令和管道的列表。

imports: [BrowserModule, SomeOtherModule]

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

本模块所导入的模块列表

exports: [MyRedComponent, MyDatePipe]

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

那些导入了本模块的模块所能看到的组件、指令和管道的列表

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

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

依赖注入提供商的列表,本模块以及本模块导入的所有模块中的内容都可以看见它们。

entryComponents: [SomeComponent, OtherComponent]

List of components not referenced in any reachable template, for example dynamically created from code.

任何未在可达模板中引用过的组件列表,比如从代码中动态创建的。

bootstrap: [MyAppComponent]

List of components to bootstrap when this module is bootstrapped.

当本模块启动时,随之启动的组件列表。

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

Binds property value to the result of expression firstName.

value属性绑定到表达式firstName

<div [attr.role]="myAriaRole">

Binds attribute role to the result of expression myAriaRole.

把属性(Attribute)role绑定到表达式myAriaRole的结果。

<div [class.extra-sparkle]="isDelightful">

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

根据isDelightful表达式的结果是否为真,决定 CSS 类extra-sparkle是否出现在当前元素上。

<div [style.width.px]="mySize">

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

把 CSS 样式属性width的 px(像素)值绑定到表达式mySize的结果。单位是可选的。

<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.

当这个按钮元素(及其子元素)上的 click 事件触发时,调用方法readRainbow,并把这个事件对象作为参数传进去。

<div title="Hello {{ponyName}}">

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

把一个属性绑定到插值字符串(如"Hello Seabiscuit")。这种写法等价于<div [title]="'Hello ' + ponyName">

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

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

把文本内容绑定到插值字符串(如"Hello Seabiscuit")

<my-cmp [(title)]="name">

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

设置双向绑定。等价于<my-cmp [title]="name" (titleChange)="name=$event">

<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.

创建一个局部变量movieplayer,支持在当前模板的数据绑定和事件绑定表达式中访问video元素的实例。

<p *myUnless="myExpression">...</p>

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

这个 * 符号会把当前元素转换成一个内嵌的模板。它等价于: <ng-template [myUnless]="myExpression"><p>...</p></ng-template>

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

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

使用名叫myCardNumberFormatter的管道对表达式cardNumber的当前值进行转换。

<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.

安全导航操作符(?)表示employer字段是可选的,如果它是 undefined ,那么表达式其余的部分就会被忽略,并返回 undefined

<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.

模板中的 SVG 片段需要给它的根元素加上svg:前缀,以便把 SVG 元素和 HTML 元素区分开。

<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.

<svg>作为根元素时会自动识别为 SVG 元素,不需要前缀。

Built-in directives 内置指令

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

<section *ngIf="showSection">

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

根据showSection表达式的结果,移除或重新创建 DOM 树的一部分。

<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.

把 li 元素及其内容变成一个模板,并使用这个模板为列表中的每一个条目实例化一个视图。

<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.

根据conditionExpression的当前值选择一个嵌入式模板,并据此决定是否替换掉这个 div 的内容。

<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.

根据 map 中的 value 是否为真,来决定该元素上是否出现与 name 对应的 CSS 类。右侧的表达式应该返回一个形如 {class-name: true/false} 的 map。

<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.

允许你使用 CSS 为 HTML 元素指定样式。你可以像第一个例子那样直接使用 CSS,也可以调用组件中的方法。

Forms 表单

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

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

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

为表单控件提供双向数据绑定、解析和验证功能。

Class decorators 类装饰器

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

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

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

声明一个类是组件,并提供该组件的元数据。

@Directive({...})
class MyDirective() {}

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

声明一个类是指令,并提供该指令的元数据。

@Pipe({...})
class MyPipe() {}

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

声明一个类是管道,并提供该管道的元数据。

@Injectable()
class MyService() {}

Declares that a class can be provided and injected by other classes. Without this decorator, the compiler won't generate enough metadata to allow the class to be created properly when it's injected somewhere.

声明某个类可以注册为提供商,并能被另一个类注入。如果没有该装饰器,编译器就不会生成足够的元数据,当它被注入到别处时,就无法正常创建该类。

Directive configuration 指令配置项

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

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

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

指定一个 CSS 选择器,用于在模板中标记出该指令。支持的选择器类型包括:元素名[属性名], .类名:not()

Does not support parent-child relationship selectors.

但不支持指定父子关系的选择器。

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

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

该指令及其子指令的依赖注入提供商列表。

Component configuration 组件配置项

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

@Component 继承自 @Directive, 因此,@Directive 的这些配置项也同样适用于组件。

moduleId: module.id

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

如果设置了,那么 templateUrlstyleUrl 的路径就会相对于当前组件进行解析。

viewProviders: [MyService, { provide: ... }]

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

依赖注入提供商列表,但它们的范围被限定为当前组件的视图。

template: 'Hello {{name}}'
templateUrl: 'my-component.html'

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

当前组件视图的内联模板或外部模板的 URL 。

styles: ['.primary {color: red}']
styleUrls: ['my-component.css']

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

用于为当前组件的视图提供样式的内联 CSS 或外部样式表 URL 的列表。

Class field decorators for directives and components 给指令和组件使用的类属性配置项

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

@Input() myProperty;

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

声明一个输入属性,你可以通过属性绑定来更新它,如 <my-cmp [myProperty]="someExpression">

@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()">).

声明一个输出属性,它发出事件,你可以用事件绑定来订阅它们(如:<my-cmp (myEvent)="doSomething()">)。

@HostBinding('class.valid') isValid;

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

把宿主元素的一个属性(这里是 CSS 类 valid)绑定到指令或组件上的 isValid 属性。

@HostListener('click', ['$event']) onClick(e) {...}

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

用指令或组件上的onClick方法订阅宿主元素上的click事件,并从中获取$event参数(可选)

@ContentChild(myPredicate) myChildComponent;

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

把组件内容查询(myPredicate)的第一个结果绑定到该类的 myChildComponent 属性上。

@ContentChildren(myPredicate) myChildComponents;

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

把组件内容查询(myPredicate)的全部结果绑定到该类的 myChildComponents 属性上

@ViewChild(myPredicate) myChildComponent;

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

把组件视图查询(myPredicate)的第一个结果绑定到该类的 myChildComponent 属性上。对指令无效。

@ViewChildren(myPredicate) myChildComponents;

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

把组件视图查询(myPredicate)的全部结果绑定到该类的 myChildComponents 属性上。对指令无效。

Directive and component change detection and lifecycle hooks 指令与组件的变更检测与生命周期钩子

(implemented as class methods)

(作为类的方法实现。)

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

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

在任何其它生命周期钩子之前调用。可以用它来注入依赖项,但不要在这里做正事。

ngOnChanges(changeRecord) { ... }

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

每当输入属性发生变化时就会调用,但位于处理内容(ng-content)或子视图之前。

ngOnInit() { ... }

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

在调用完构造函数、初始化完所有输入属性并首次调用过ngOnChanges之后调用。

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.

每当对组件或指令的输入属性进行变更检测时就会调用。可以用它来扩展变更检测逻辑,执行自定义的检测逻辑。

ngAfterContentInit() { ... }

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

ngOnInit完成之后,当组件或指令的内容(ng-content)已经初始化完毕时调用。

ngAfterContentChecked() { ... }

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

每当组件或指令的内容(ng-content)做变更检测时调用。

ngAfterViewInit() { ... }

Called after ngAfterContentInit when the component's views and child views / the view that a directive is in has been initialized.

ngAfterContentInit完毕,并且组件的视图及其子视图或指令所属的视图已经初始化完毕时调用。

ngAfterViewChecked() { ... }

Called after every check of the component's views and child views / the view that a directive is in.

当组件的视图及其子视图或指令所属的视图每次执行变更检测时调用。

ngOnDestroy() { ... }

Called once, before the instance is destroyed.

只在实例被销毁前调用一次。

Dependency injection configuration 依赖注入配置项
{ provide: MyService, useClass: MyMockService }

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

MyService 的服务提供商设置或改写为 MyMockService 类。

{ provide: MyService, useFactory: myFactory }

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

MyService 的服务提供商设置或改写为 myFactory 工厂函数。

{ provide: MyValue, useValue: 41 }

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

MyValue 的服务提供商改写为一个特定的值 41

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);

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

为该应用配置路由。支持静态、参数化、重定向和通配符路由。也支持自定义路由数据和解析(resolve)函数。


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

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

标记出一个位置,用来加载活动路由的组件。


<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.

使用路由体系创建一个到其它视图的链接。路由体系由路由路径、必要参数、可选参数、查询参数和文档片段组成。要导航到根路由,请使用/前缀;要导航到子路由,使用./前缀;要导航到兄弟路由或父级路由,使用../前缀。

<a [routerLink]="[ '/path' ]" routerLinkActive="active">

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

routerLink 指向的路由变成活动路由时,为当前元素添加一些类(比如这里的 active)。

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

{ 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|UrlTree or an Observable/Promise that resolves to a boolean|UrlTree.

用来定义类的接口。路由器会首先调用本接口来决定是否激活该路由。应该返回一个 boolean|UrlTree 或能解析成 boolean|UrlTreeObservable/Promise

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

{ 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|UrlTree or an Observable/Promise that resolves to a boolean|UrlTree.

用来定义类的接口。路由器会在导航离开前首先调用本接口以决定是否取消激活本路由。应该返回一个 boolean|UrlTree 或能解析成 boolean|UrlTreeObservable/Promise

class CanActivateChildGuard implements CanActivateChild {
canActivateChild(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree { ... }
}

{ 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|UrlTree or an Observable/Promise that resolves to a boolean|UrlTree.

用来定义类的接口。路由器会首先调用本接口来决定是否激活一个子路由。应该返回一个 boolean|UrlTree 或能解析成 boolean|UrlTreeObservable/Promise

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.

用来定义类的接口。路由器会在渲染该路由之前,首先调用它来解析路由数据。应该返回一个值或能解析成值的 Observable/Promise

class CanLoadGuard implements CanLoad {
canLoad(
route: Route
): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree { ... }
}

{ 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|UrlTree or an Observable/Promise that resolves to a boolean|UrlTree.

用来定义类的接口。路由器会首先调用它来决定是否应该加载一个惰性加载模块。应该返回一个 boolean|UrlTree 或能解析成 boolean|UrlTreeObservable/Promise