填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫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.