填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

速查表

Cheat Sheet

引导/启动

Bootstrapping

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

platformBrowserDynamic().bootstrapModule(AppModule);

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

Bootstraps the app, using the root component from the specified 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">

value属性绑定到表达式firstName

Binds property value to the result of expression firstName.

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

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

Binds attribute role to the result of expression myAriaRole.

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

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

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

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

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

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

<button (click)="readRainbow($event)">

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

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

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

把一个属性绑定到插值字符串(如"Hello Seabiscuit")。这种写法等价于<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>

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

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

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

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

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

<video #movieplayer ...>
<button (click)="movieplayer.play()">
</video>

创建一个局部变量movieplayer,支持在当前模板的数据绑定和事件绑定表达式中访问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.

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

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

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>

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

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

<p>Employer: {{employer?.companyName}}</p>

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

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

<svg:rect x="0" y="0" width="100" height="100"/>

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

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

<svg>
<rect x="0" y="0" width="100" height="100"/>
</svg>

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

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

内置指令

Built-in directives

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

<section *ngIf="showSection">

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

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

<li *ngFor="let item of list">

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

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

<div [ngSwitch]="conditionExpression">
<ng-template [ngSwitchCase]="case1Exp">...</ng-template>
<ng-template ngSwitchCase="case2LiteralString">...</ng-template>
<ng-template ngSwitchDefault>...</ng-template>
</div>

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

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

<div [ngClass]="{'active': isActive, 'disabled': isDisabled}">

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

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

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

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

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

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

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.

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

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

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

组件配置项

Component configuration

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

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

moduleId: module.id

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

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

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

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

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

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

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

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

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

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

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

给指令和组件使用的类属性配置项

Class field decorators for directives and components

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

@Input() myProperty;

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

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

@Output() myEvent = new EventEmitter();

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

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

@HostBinding('class.valid') isValid;

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

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

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

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

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

@ContentChild(myPredicate) myChildComponent;

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

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

@ContentChildren(myPredicate) myChildComponents;

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

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

@ViewChild(myPredicate) myChildComponent;

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

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

@ViewChildren(myPredicate) myChildComponents;

把组件视图查询(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

(作为类的方法实现。)

(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) { ... }

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

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

ngOnInit() { ... }

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

Called after the constructor, initializing input properties, and the first call to 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() { ... }

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

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

ngAfterContentChecked() { ... }

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

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

ngAfterViewInit() { ... }

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

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

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 }

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

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

{ provide: MyService, useFactory: myFactory }

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

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

{ provide: MyValue, useValue: 41 }

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

Sets or overrides the provider for MyValue to the value 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);

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

Configures routes for the application. Supports static, parameterized, redirect, and wildcard routes. Also supports custom route data and 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">

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

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

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

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

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

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.

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

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

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

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.

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

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

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

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.

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

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

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

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.

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

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

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

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.