填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

關於 AngularJS 與 Angular 概念的快速參考

AngularJS to Angular concepts: Quick reference

Angular 這個名字專指現在和未來的 Angular 版本,而 AngularJS 專指 Angular 的所有 v1.x 版本。

Angular is the name for the Angular of today and tomorrow. AngularJS is the name for all v1.x versions of Angular.

本章提供了一個快速的參考指南,指出一些常用的 AngularJS 語法及其在 Angular 中的等價物。

This guide helps you transition from AngularJS to Angular by mapping AngularJS syntax to the equivalent Angular syntax.

參閱現場演練 / 下載範例以學習 Angular 語法

See the Angular syntax in this現場演練 / 下載範例.

範本基礎

Template basics

範本是 Angular 應用中的門面部分,它是用 HTML 寫的。下表中是一些 AngularJS 中的關鍵範本特性及其在 Angular 中的等價語法。

Templates are the user-facing part of an Angular application and are written in HTML. The following table lists some of the key AngularJS template features with their equivalent Angular template syntax.

AngularJS

Angular

繫結/插值

Bindings/interpolation

Your favorite hero is: {{vm.favoriteHero}}
      
      Your favorite hero is: {{vm.favoriteHero}}
    

在 AngularJS 中,花括號中的表示式代表單向繫結。 它把元素的值繫結到了與範本相關控制器的屬性上。

In AngularJS, an expression in curly braces denotes one-way binding. This binds the value of the element to a property in the controller associated with this template.

當使用 controller as 語法時,該繫結需要用控制器的別名(vm)為字首,這是因為你不得不透過它來指定繫結源。

When using the controller as syntax, the binding is prefixed with the controller alias (vm or $ctrl) because you have to be specific about the source of the binding.

繫結/插值

Bindings/interpolation

Your favorite hero is: {{favoriteHero}}
      
      Your favorite hero is: {{favoriteHero}}
    

在 Angular 中,花括號中的範本表示式同樣代表單向繫結。 它把元素的值繫結到了元件的屬性上。 它繫結的上下文變數是隱式的,並且總是關聯到元件。 所以,它不需要一個參考變數。

In Angular, a template expression in curly braces still denotes one-way binding. This binds the value of the element to a property of the component. The context of the binding is implied and is always the associated component, so it needs no reference variable.

要了解更多,請參閱插值部分。

For more information, see the Interpolation guide.

過濾器

Filters

<td>{{movie.title | uppercase}}</td>
      
      <td>{{movie.title | uppercase}}</td>
    

要在 AngularJS 中過濾輸出,使用管道字元(|)以及一個或多個過濾器。

To filter output in AngularJS templates, use the pipe character (|) and one or more filters.

這個例子中把 title 屬性過濾成了大寫形式。

This example filters the title property to uppercase.

管道

Pipes

<td>{{movie.title | uppercase}}</td>
      
      <td>{{movie.title | uppercase}}</td>
    

在 Angular 中,你使用類似的語法 —— 用管道字元(|)來過濾輸出,但是現在直接把它叫做管道了。 很多(但不是所有)AngularJS 中的內建過濾器也成了 Angular 中的內建管道。

In Angular you use similar syntax with the pipe (|) character to filter output, but now you call them pipes. Many (but not all) of the built-in filters from AngularJS are built-in pipes in Angular.

請參閱下面過濾器/管道瞭解更多資訊。

For more information, see Filters/pipes below.

區域性變數

Local variables

<tr ng-repeat="movie in vm.movies"> <td>{{movie.title}}</td> </tr>
      
      <tr ng-repeat="movie in vm.movies">
  <td>{{movie.title}}</td>
</tr>
    

這裡的 movie 是一個使用者定義的區域性變數

Here, movie is a user-defined local variable.

輸入變數

Input variables

<tr *ngFor="let movie of movies"> <td>{{movie.title}}</td> </tr>
      
      <tr *ngFor="let movie of movies">
  <td>{{movie.title}}</td>
</tr>
    

Angular 有了真正的範本輸入變數,它需要使用 let 關鍵字進行明確定義。

Angular has true template input variables that are explicitly defined using the let keyword.

要了解更多資訊,請參閱內建指令中的ngFor 微語法部分。

For more information, see the ngFor micro-syntax section of the Built-in Directives page.

範本指令

Template directives

AngularJS 為範本提供了七十多個內建指令。 在 Angular 中,它們很多都已經不需要了,因為 Angular 有了一個更加強大、快捷的繫結系統。 下面是一些 AngularJS 中的關鍵指令及其在 Angular 中的等價物。

AngularJS provides more than seventy built-in directives for templates. Many of them aren't needed in Angular because of its more capable and expressive binding system. The following are some of the key AngularJS built-in directives and their equivalents in Angular.

AngularJS

Angular

ng-app

<body ng-app="movieHunter">
      
      <body ng-app="movieHunter">
    

應用的啟動過程被稱為引導

The application startup process is called bootstrapping.

雖然可以從程式碼中引導 Angular 應用, 但很多應用都是透過 ng-app 指令進行宣告式引導的,只要給它一個應用模組的名字(movieHunter)就可以了。

Although you can bootstrap an AngularJS app in code, many applications bootstrap declaratively with the ng-app directive, giving it the name of the application's module (movieHunter).

引導

Bootstrapping

import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic().bootstrapModule(AppModule);
main.ts
      
      import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);
    

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
app.module.ts
      
      import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
    

Angular 沒有引導指令。 總是要透過顯式呼叫一個 bootstrap 函式,並傳入應用模組的名字(AppComponent)來啟動應用。

Angular doesn't have a bootstrap directive. To launch the app in code, explicitly bootstrap the application's root module (AppModule) in main.ts and the application's root component (AppComponent) in app.module.ts.

ng-class

<div ng-class="{active: isActive}"> <div ng-class="{active: isActive, shazam: isImportant}">
      
      <div ng-class="{active: isActive}">
<div ng-class="{active: isActive,
                   shazam: isImportant}">
    

在 AngularJS 中,ng-class 指令會基於一個表示式來包含/排除某些 CSS 類別。該表示式通常是一個“鍵-值”型的控制物件, 物件中的每一個鍵代表一個 CSS 類別名稱,每一個值定義為一個返回布林值的範本表示式。

In AngularJS, the ng-class directive includes/excludes CSS classes based on an expression. That expression is often a key-value control object with each key of the object defined as a CSS class name, and each value defined as a template expression that evaluates to a Boolean value.

在第一個例子中,如果 isActive 為真,則 active 類別被應用到那個元素上。

In the first example, the active class is applied to the element if isActive is true.

就像第二個例子中所展示的那樣,可以同時指定多個類別。

You can specify multiple classes, as shown in the second example.

ngClass

<div [ngClass]="{'active': isActive}"> <div [ngClass]="{'active': isActive, 'shazam': isImportant}"> <div [class.active]="isActive">
      
      <div [ngClass]="{'active': isActive}">
<div [ngClass]="{'active': isActive,
                 'shazam': isImportant}">
<div [class.active]="isActive">
    

在 Angular 中,ngClass 指令用類似的方式工作。 它根據一個表示式包含/排除某些 CSS 類別。

In Angular, the ngClass directive works similarly. It includes/excludes CSS classes based on an expression.

在第一個例子中,如果 isActive 為真,則 active 類別被應用到那個元素上。

In the first example, the active class is applied to the element if isActive is true.

就像第二個例子中所展示的那樣,可以同時指定多個類別。

You can specify multiple classes, as shown in the second example.

Angular 還有類別繫結,它是單獨新增或移除一個類別的好辦法 —— 就像第三個例子中展示的。

Angular also has class binding, which is a good way to add or remove a single class, as shown in the third example.

要了解更多資訊,參閱屬性(Attribute)繫結、類別繫結和樣式繫結部分。

For more information see Attribute, class, and style bindings page.

ng-click

<button ng-click="vm.toggleImage()"> <button ng-click="vm.toggleImage($event)">
      
      <button ng-click="vm.toggleImage()">
<button ng-click="vm.toggleImage($event)">
    

在 AngularJS 中,ng-click 指令指定當元素被點選時的自訂行為。

In AngularJS, the ng-click directive allows you to specify custom behavior when an element is clicked.

在第一個例子中,如果使用者點選了這個按鈕,那麼控制器的 toggleImage() 方法就會被執行,這個控制器是被 controller as 中指定的 vm 別名所參考的。

In the first example, when the user clicks the button, the toggleImage() method in the controller referenced by the vm controller as alias is executed.

第二個例子示範了傳入 $event 物件,它提供了事件的詳情,並被傳到控制器。

The second example demonstrates passing in the $event object, which provides details about the event to the controller.

繫結到 click 事件

Bind to the click event

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

AngularJS 基於事件的指令在 Angular 中已經不存在了。 不過,可以使用事件繫結來定義從範本檢視到元件的單向資料繫結。

AngularJS event-based directives do not exist in Angular. Rather, define one-way binding from the template view to the component using event binding.

要使用事件繫結,把目標事件的名字放在圓括號中,並且使用等號右側引號中的範本語句對它賦值。 然後 Angular 為這個目標時間設定事件處理器。當事件被觸發時,這個處理器就會執行範本語句。

For event binding, define the name of the target event within parenthesis and specify a template statement, in quotes, to the right of the equals. Angular then sets up an event handler for the target event. When the event is raised, the handler executes the template statement.

在第一個例子中,當用戶點選此按鈕時,相關元件中的 toggleImage() 方法就被執行了。

In the first example, when a user clicks the button, the toggleImage() method in the associated component is executed.

第二個例子示範瞭如何傳入 $event 物件,它為元件提供了此事件的詳情。

The second example demonstrates passing in the $event object, which provides details about the event to the component.

要檢視 DOM 事件的列表,請參閱網路事件

For a list of DOM events, see: https://developer.mozilla.org/en-US/docs/Web/Events.

要了解更多,請參閱事件繫結頁。

For more information, see the Event binding page.

ng-controller

<div ng-controller="MovieListCtrl as vm">
      
      <div ng-controller="MovieListCtrl as vm">
    

在 AngularJS 中,ng-controller 指令把控制器附加到檢視上。 使用 ng-controller(或把控制器定義為路由的一部分)把檢視及其控制器的程式碼聯絡在一起。

In AngularJS, the ng-controller directive attaches a controller to the view. Using the ng-controller (or defining the controller as part of the routing) ties the view to the controller code associated with that view.

元件裝飾器

Component decorator

@Component({ selector: 'app-movie-list', templateUrl: './movie-list.component.html', styleUrls: [ './movie-list.component.css' ], })
      
      @Component({
  selector: 'app-movie-list',
  templateUrl: './movie-list.component.html',
  styleUrls: [ './movie-list.component.css' ],
})
    

在 Angular 中,範本不用再指定它相關的控制器。 反過來,元件會在元件類別的裝飾器中指定與它相關的範本。

In Angular, the template no longer specifies its associated controller. Rather, the component specifies its associated template as part of the component class decorator.

要了解更多,請參閱架構概覽

For more information, see Architecture Overview.

ng-hide

在 AngularJS 中,ng-hide 指令會基於一個表示式顯示或隱藏相關的 HTML 元素。 參閱ng-show瞭解更多。

In AngularJS, the ng-hide directive shows or hides the associated HTML element based on an expression. For more information, see ng-show.

繫結到 hidden 屬性

Bind to the hidden property

在 Angular 中,並沒有一個內建的 hide 指令,可以改用屬性繫結。 參閱ng-show瞭解更多。

In Angular, you use property binding; there is no built-in hide directive. For more information, see ng-show.

ng-href

<a ng-href="{{ angularDocsUrl }}">Angular Docs</a>
      
      <a ng-href="{{ angularDocsUrl }}">Angular Docs</a>
    

ng-href 指令允許 AngularJS 對 href 屬性進行預處理,以便它能在瀏覽器獲取那個 URL 之前,使用一個返回適當 URL 的繫結表示式替換它。

The ng-href directive allows AngularJS to preprocess the href property so that it can replace the binding expression with the appropriate URL before the browser fetches from that URL.

在 AngularJS 中,ng-href 通常用來作為導航的一部分,啟用一個路由。

In AngularJS, the ng-href is often used to activate a route as part of navigation.

<a ng-href="#{{ moviesHash }}">Movies</a>
      
      <a ng-href="#{{ moviesHash }}">Movies</a>
    

路由在 Angular 中的處理方式不同。

Routing is handled differently in Angular.

繫結到 href 屬性

Bind to the href property

<a [href]="angularDocsUrl">Angular Docs</a>
      
      <a [href]="angularDocsUrl">Angular Docs</a>
    

在 Angular 中,並沒有內建的 href 指令,改用屬性繫結。 把元素的 href 屬性放在方括號中,並把它設成一個引號中的範本表示式。

Angular uses property binding; there is no built-in href directive. Place the element's href property in square brackets and set it to a quoted template expression.

欲知詳情,參閱屬性繫結頁。

For more information see the Property binding page.

在 Angular 中,href 不再用作路由,而是改用第三個例子中所展示的 routerLink 指令。

In Angular, href is no longer used for routing. Routing uses routerLink, as shown in the following example.

<a [routerLink]="['/movies']">Movies</a>
      
      <a [routerLink]="['/movies']">Movies</a>
    

要了解關於路由的更多資訊,請參閱路由與導航定義基礎路由部分。

For more information on routing, see Defining a basic route in the Routing & Navigation page.

ng-if

<table ng-if="movies.length">
      
      <table ng-if="movies.length">
    

在 AngularJS 中,ng-if 指令會根據一個表示式來移除或重建 DOM 中的一部分。如果表示式為假,元素就會被從 DOM 中移除。

In AngularJS, the ng-if directive removes or recreates a portion of the DOM, based on an expression. If the expression is false, the element is removed from the DOM.

在這個例子中,除非 movies 陣列的長度大於 0,否則 <table> 元素就會被從 DOM 中移除。

In this example, the <table> element is removed from the DOM unless the movies array has a length greater than zero.

*ngIf

<table *ngIf="movies.length">
      
      <table *ngIf="movies.length">
    

Angular 中的 *ngIf 指令與 AngularJS 中的 ng-if 指令一樣, 它根據表示式的值移除或重建 DOM 中的一部分。

The *ngIf directive in Angular works the same as the ng-if directive in AngularJS. It removes or recreates a portion of the DOM based on an expression.

在這個例子中,除非 movies 陣列的長度大於 0,否則 <table> 元素就會被從 DOM 中移除。

In this example, the <table> element is removed from the DOM unless the movies array has a length.

在這個例子中 ngIf 前的星號(*)是必須的。 要了解更多資訊,參閱結構型指令

The (*) before ngIf is required in this example. For more information, see Structural Directives.

ng-model

<input ng-model="vm.favoriteHero"/>
      
      <input ng-model="vm.favoriteHero"/>
    

在 AngularJS 中,ng-model 指令把一個表單控制元件繫結到了範本相關控制器的一個屬性上。 這提供了雙向繫結功能,因此,任何對檢視中值的改動,都會同步到模型中,對模型的改動,也會同步到檢視中。

In AngularJS, the ng-model directive binds a form control to a property in the controller associated with the template. This provides two-way binding, whereby any change made to the value in the view is synchronized with the model, and any change to the model is synchronized with the value in the view.

ngModel

<input [(ngModel)]="favoriteHero" />
      
      <input [(ngModel)]="favoriteHero" />
    

在 Angular 中,雙向繫結使用[()]標記出來,它被形象的比作“盒子中的香蕉”。 這種語法是一個簡寫形式,用來同時定義一個屬性繫結(從元件到檢視)和一個事件繫結(從檢視到元件),就成了雙向繫結。

In Angular, two-way binding is denoted by [()], descriptively referred to as a "banana in a box". This syntax is a shortcut for defining both property binding (from the component to the view) and event binding (from the view to the component), thereby providing two-way binding.

要了解使用 ngModel 進行雙向繫結的更多知識,參閱內建指令中的[(ngModel)]](../guide/built-in-directives#ngModel)部分。

For more information on two-way binding with ngModel, see the NgModel—Two-way binding to form elements with [(ngModel)]section of the Built-in directives page.

ng-repeat

<tr ng-repeat="movie in vm.movies">
      
      <tr ng-repeat="movie in vm.movies">
    

在 AngularJS 中,ng-repeat 指令會為指定集合中的每一個條目重複渲染相關的 DOM 元素。

In AngularJS, the ng-repeat directive repeats the associated DOM element for each item in the specified collection.

在這個例子中,對 movies 集合中的每一個 movie 物件重複渲染了這個表格行元素(<tr>)。

In this example, the table row (<tr>) element repeats for each movie object in the collection of movies.

*ngFor

<tr *ngFor="let movie of movies">
      
      <tr *ngFor="let movie of movies">
    

Angular 中的 *ngFor 指令類似於 AngularJS 中的 ng-repeat 指令。 它為指定集合中的每一個條目重複渲染了相關的 DOM 元素。 更準確的說,它把被界定出來的元素(這個例子中是 <tr>)及其內容轉成了一個範本,並使用那個範本來為列表中的每一個條目實例化一個檢視。

The *ngFor directive in Angular is similar to the ng-repeat directive in AngularJS. It repeats the associated DOM element for each item in the specified collection. More accurately, it turns the defined element (<tr> in this example) and its contents into a template and uses that template to instantiate a view for each item in the list.

請注意其它語法上的差異: 在 ngFor 前面的星號(*)是必須的;let 關鍵字把 movie 標記成一個輸入變數;列表中使用的介詞是 of,而不再是 in

Notice the other syntax differences: The (*) before ngFor is required; the let keyword identifies movie as an input variable; the list preposition is of, not in.

要了解更多資訊,參閱結構性指令

For more information, see Structural Directives.

ng-show

<h3 ng-show="vm.favoriteHero"> Your favorite hero is: {{vm.favoriteHero}} </h3>
      
      <h3 ng-show="vm.favoriteHero">
  Your favorite hero is: {{vm.favoriteHero}}
</h3>
    

在 AngularJS 中,ng-show 指令根據一個表示式來顯示或隱藏相關的 DOM 元素。

In AngularJS, the ng-show directive shows or hides the associated DOM element, based on an expression.

在這個例子中,如果 favoriteHero 變數為真,<div> 元素就會顯示出來。

In this example, the <div> element is shown if the favoriteHero variable is truthy.

繫結到 hidden 屬性

Bind to the hidden property

<h3 [hidden]="!favoriteHero"> Your favorite hero is: {{favoriteHero}} </h3>
      
      <h3 [hidden]="!favoriteHero">
  Your favorite hero is: {{favoriteHero}}
</h3>
    

在 Angular 中,並沒有內建的 show 指令,可以改用屬性繫結。 要隱藏或顯示一個元素,繫結到它的 hidden 屬性就可以了。

Angular uses property binding; there is no built-in show directive. For hiding and showing elements, bind to the HTML hidden property.

要想有條件的顯示一個元素,就把該元素的 hidden 屬性放到一個方括號裡,並且把它設定為引號中的範本表示式,它的結果應該是與顯示相反的值。

To conditionally display an element, place the element's hidden property in square brackets and set it to a quoted template expression that evaluates to the opposite of show.

在這個例子中,如果 favoriteHero 變數不是真值,<div> 元素就會被隱藏。

In this example, the <div> element is hidden if the favoriteHero variable is not truthy.

要了解屬性繫結的更多知識,參閱屬性繫結頁。

For more information on property binding, see the Property binding page.

ng-src

<img ng-src="{{movie.imageurl}}">
      
      <img ng-src="{{movie.imageurl}}">
    

ng-src 指令允許 AngularJS 對 src 屬性進行預處理,以便它能夠在瀏覽器獲取此 URL 之前,用一個返回適當 URL 的繫結表示式替換它。

The ng-src directive allows AngularJS to preprocess the src property so that it can replace the binding expression with the appropriate URL before the browser fetches from that URL.

繫結到 src 屬性

Bind to the src property

<img [src]="movie.imageurl">
      
      <img [src]="movie.imageurl">
    

在 Angular 中,並沒有一個內建的 src 指令,可以使用屬性繫結。 把 src 屬性放到方括號中,並且把它設為一個引號中的繫結表示式。

Angular uses property binding; there is no built-in src directive. Place the src property in square brackets and set it to a quoted template expression.

要了解關於屬性繫結的更多知識,參閱屬性繫結頁。

For more information on property binding, see the Property binding page.

ng-style

<div ng-style="{color: colorPreference}">
      
      <div ng-style="{color: colorPreference}">
    

在 AngularJS 中,ng-style 指令根據一個繫結表示式設定一個 HTML 元素的 CSS 樣式。 該表示式通常是一個“鍵-值”形式的控制物件,物件的每個鍵都是一個 CSS 屬性,每個值都是一個能計算為此樣式的合適值的表示式。

In AngularJS, the ng-style directive sets a CSS style on an HTML element based on an expression. That expression is often a key-value control object with each key of the object defined as a CSS property, and each value defined as an expression that evaluates to a value appropriate for the style.

在這個例子中,color 樣式被設定為 colorPreference 變數的當前值。

In the example, the color style is set to the current value of the colorPreference variable.

ngStyle

<div [ngStyle]="{'color': colorPreference}"> <div [style.color]="colorPreference">
      
      <div [ngStyle]="{'color': colorPreference}">
<div [style.color]="colorPreference">
    

在 Angular 中,ngStyle 指令的工作方式與此類似。它根據一個表示式設定 HTML 元素上的 CSS 樣式。

In Angular, the ngStyle directive works similarly. It sets a CSS style on an HTML element based on an expression.

在第一個例子中,color 樣式被設定成了 colorPreference 變數的當前值。

In the first example, the color style is set to the current value of the colorPreference variable.

Angular 還有樣式繫結語法,它是單獨設定一個樣式的好方法。它展示在第二個例子中。

Angular also has style binding, which is good way to set a single style. This is shown in the second example.

要了解關於樣式繫結的更多知識,參閱屬性繫結中的樣式繫結部分。

For more information on style binding, see the Style binding section of the Attribute binding page.

要了解關於 ngStyle 指令的更多知識,參閱內建指令中的NgStyle部分。

For more information on the ngStyle directive, see the NgStyle section of the Built-in directives page.

ng-switch

<div ng-switch="vm.favoriteHero && vm.checkMovieHero(vm.favoriteHero)"> <div ng-switch-when="true"> Excellent choice! </div> <div ng-switch-when="false"> No movie, sorry! </div> <div ng-switch-default> Please enter your favorite hero. </div> </div>
      
      <div ng-switch="vm.favoriteHero &&
                vm.checkMovieHero(vm.favoriteHero)">
    <div ng-switch-when="true">
      Excellent choice!
    </div>
    <div ng-switch-when="false">
      No movie, sorry!
    </div>
    <div ng-switch-default>
      Please enter your favorite hero.
    </div>
</div>
    

在 AngularJS 中,ng-switch 指令根據一個表示式的當前值把元素的內容替換成幾個範本之一。

In AngularJS, the ng-switch directive swaps the contents of an element by selecting one of the templates based on the current value of an expression.

在這個例子中,如果 favoriteHero 沒有設定,則範本顯示“Please enter ...”。 如果 favoriteHero 設定過,它就會透過呼叫一個控制其方法來檢查它是否電影裡的英雄。 如果該方法返回 true,範本就會顯示“Excellent choice!”。 如果該方法返回 false,該範本就會顯示“No movie, sorry!”。

In this example, if favoriteHero is not set, the template displays "Please enter ...". If favoriteHero is set, it checks the movie hero by calling a controller method. If that method returns true, the template displays "Excellent choice!". If that methods returns false, the template displays "No movie, sorry!".

ngSwitch

<span [ngSwitch]="favoriteHero && checkMovieHero(favoriteHero)"> <p *ngSwitchCase="true"> Excellent choice! </p> <p *ngSwitchCase="false"> No movie, sorry! </p> <p *ngSwitchDefault> Please enter your favorite hero. </p> </span>
      
      <span [ngSwitch]="favoriteHero &&
               checkMovieHero(favoriteHero)">
  <p *ngSwitchCase="true">
    Excellent choice!
  </p>
  <p *ngSwitchCase="false">
    No movie, sorry!
  </p>
  <p *ngSwitchDefault>
    Please enter your favorite hero.
  </p>
</span>
    

在 Angular 中,ngSwitch 指令的工作方式與此類似。 它會顯示那個與 ngSwitch 表示式的當前值匹配的那個 *ngSwitchCase 所在的元素。

In Angular, the ngSwitch directive works similarly. It displays an element whose *ngSwitchCase matches the current ngSwitch expression value.

在這個例子中,如果 favoriteHero 沒有設定,則 ngSwitch 的值是 null*ngSwitchDefault 中會顯示 “Please enter ...”。 如果設定了 favoriteHero,應用就會透過呼叫一個元件方法來檢查電影英雄。 如果該方法返回 true,就會顯示 “Excellent choice!”。 如果該方法返回 false,就會顯示 “No movie, sorry!”。

In this example, if favoriteHero is not set, the ngSwitch value is null and *ngSwitchDefault displays, "Please enter ...". If favoriteHero is set, the app checks the movie hero by calling a component method. If that method returns true, the app selects *ngSwitchCase="true" and displays: "Excellent choice!" If that methods returns false, the app selects *ngSwitchCase="false" and displays: "No movie, sorry!"

在這個例子中,ngSwitchCasengSwitchDefault 前面的星號(*)是必須的。

The (*) before ngSwitchCase and ngSwitchDefault is required in this example.

要了解更多資訊,參閱內建指令中的NgSwitch 指令部分。

For more information, see The NgSwitch directives section of the Built-in directives page.

過濾器/管道

Filters/pipes

Angular 中的管道為範本提供了格式化和資料轉換功能,類似於 AngularJS 中的過濾器。 AngularJS 中的很多內建過濾器在 Angular 中都有對應的管道。 要了解管道的更多資訊,參閱Pipes

Angular pipes provide formatting and transformation for data in the template, similar to AngularJS filters. Many of the built-in filters in AngularJS have corresponding pipes in Angular. For more information on pipes, see Pipes.

AngularJS

Angular

currency

<td>{{movie.price | currency}}</td>
      
      <td>{{movie.price | currency}}</td>
    

把一個數字格式化成貨幣。

Formats a number as currency.

currency

<td>{{movie.price | currency:'USD':true}}</td>
      
      <td>{{movie.price | currency:'USD':true}}</td>
    

Angular 的 currency 管道和 1 中很相似,只是有些引數變化了。

The Angular currency pipe is similar although some of the parameters have changed.

date

<td>{{movie.releaseDate | date}}</td>
      
      <td>{{movie.releaseDate | date}}</td>
    

基於要求的格式把日期格式化成字串。

Formats a date to a string based on the requested format.

date

<td>{{movie.releaseDate | date}}</td>
      
      <td>{{movie.releaseDate | date}}</td>
    

Angular 的 date 管道和它很相似。

The Angular date pipe is similar.

filter

<tr ng-repeat="movie in movieList | filter: {title:listFilter}">
      
      <tr ng-repeat="movie in movieList | filter: {title:listFilter}">
    

根據過濾條件從指定的集合中選取出一個子集。

Selects a subset of items from the defined collection, based on the filter criteria.

沒了

none

在 Angular 中,出於效能的考慮,並沒有一個類似的管道。 過濾邏輯應該在元件中用程式碼實現。 如果它將被複用在幾個範本中,可以考慮建構一個自訂管道。

For performance reasons, no comparable pipe exists in Angular. Do all your filtering in the component. If you need the same filtering code in several templates, consider building a custom pipe.

json

<pre>{{movie | json}}</pre>
      
      <pre>{{movie | json}}</pre>
    

把一個 JavaScript 物件轉換成一個 JSON 字串。這對除錯很有用。

Converts a JavaScript object into a JSON string. This is useful for debugging.

json

<pre>{{movie | json}}</pre>
      
      <pre>{{movie | json}}</pre>
    

Angular 的 json 管道做完全相同的事。

The Angular json pipe does the same thing.

limitTo

<tr ng-repeat="movie in movieList | limitTo:2:0">
      
      <tr ng-repeat="movie in movieList | limitTo:2:0">
    

從集合中選擇從(第二引數指定的)起始索引號(0)開始的最多(第一引數指定的)條目數(2)個條目。

Selects up to the first parameter (2) number of items from the collection starting (optionally) at the beginning index (0).

slice

<tr *ngFor="let movie of movies | slice:0:2">
      
      <tr *ngFor="let movie of movies | slice:0:2">
    

SlicePipe 做同樣的事,但是兩個引數的順序是相反的,以便於 JavaScript 中的 slice 方法保持一致。 第一個引數是起始索引號,第二個引數是限制的數量。 和 AngularJS 中一樣,如果們改用元件中的程式碼實現此操作,效能將會提升。

The SlicePipe does the same thing but the order of the parameters is reversed, in keeping with the JavaScript Slice method. The first parameter is the starting index; the second is the limit. As in AngularJS, coding this operation within the component instead could improve performance.

lowercase

<td>{{movie.title | lowercase}}</td>
      
      <td>{{movie.title | lowercase}}</td>
    

把該字串轉成小寫形式。

Converts the string to lowercase.

lowercase

<td>{{movie.title | lowercase}}</td>
      
      <td>{{movie.title | lowercase}}</td>
    

Angular 的 lowercase 管道和 1 中的功能完全相同。

The Angular lowercase pipe does the same thing.

number

<td>{{movie.starRating | number}}</td>
      
      <td>{{movie.starRating | number}}</td>
    

把數字格式化為文字。

Formats a number as text.

number

<td>{{movie.starRating | number}}</td> <td>{{movie.starRating | number:'1.1-2'}}</td> <td>{{movie.approvalRating | percent: '1.0-2'}}</td>
      
      <td>{{movie.starRating | number}}</td>
<td>{{movie.starRating | number:'1.1-2'}}</td>
<td>{{movie.approvalRating | percent: '1.0-2'}}</td>
    

Angular 的 number 管道很相似。 但在指定小數點位置時,它提供了更多的功能,如第二個範例所示。

The Angular number pipe is similar. It provides more functionality when defining the decimal places, as shown in the second example above.

Angular 還有一個 percent 管道,它把一個數組格式化為本地化的(local)百分比格式,如第三個範例所示。

Angular also has a percent pipe, which formats a number as a local percentage as shown in the third example.

orderBy

<tr ng-repeat="movie in movieList | orderBy : 'title'">
      
      <tr ng-repeat="movie in movieList | orderBy : 'title'">
    

使用表示式中所指定的方式對集合進行排序。 在這個例子中,movieList 被根據 movie 的 title 排序了。

Displays the collection in the order specified by the expression. In this example, the movie title orders the movieList.

沒了

none

在 Angular 中,出於效能的考慮,並沒有一個類似的管道。 排序邏輯應該在元件中用程式碼實現。 如果它將被複用在幾個範本中,可以考慮建構一個自訂管道。

For performance reasons, no comparable pipe exists in Angular. Instead, use component code to order or sort results. If you need the same ordering or sorting code in several templates, consider building a custom pipe.

模組/控制器/元件

Modules/controllers/components

無論在 AngularJS 還是 Angular 中,“模組”都會幫你把應用拆分成一些內聚的功能塊。

In both AngularJS and Angular, modules help you organize your application into cohesive blocks of functionality.

在 AngularJS 中,你要在控制器中寫程式碼,來為檢視提供模型和方法。 在 Angular 中,你要建立元件

In AngularJS, you write the code that provides the model and the methods for the view in a controller. In Angular, you build a component.

因為很多 AngularJS 的程式碼是用 JavaScript 寫的,所以在 AngularJS 列顯示的是 JavaScript 程式碼,而 Angular 列顯示的是 TypeScript 程式碼。

Because much AngularJS code is in JavaScript, JavaScript code is shown in the AngularJS column. The Angular code is shown using TypeScript.

AngularJS

Angular

IIFE

(function () { ... }());
      
      (function () {
  ...
}());
    

在 AngularJS 中,用立即呼叫的函式表示式(IIFE)來包裹控制器程式碼可以讓控制器程式碼不會汙染全域性名稱空間。

In AngularJS, an immediately invoked function expression (or IIFE) around controller code keeps it out of the global namespace.

沒了

none

在 Angular 中不用擔心這個問題,因為使用 ES 2015 的模組,模組會替你處理名稱空間問題。

This is a nonissue in Angular because ES 2015 modules handle the namespacing for you.

要了解關於模組的更多資訊,參閱架構概覽中的模組部分。

For more information on modules, see the Modules section of the Architecture Overview.

Angular 模組

Angular modules

angular.module("movieHunter", ["ngRoute"]);
      
      angular.module("movieHunter", ["ngRoute"]);
    

在 AngularJS 中,Angular 模組用來對控制器、服務和其它程式碼進行追蹤。第二個引數定義該模組依賴的其它模組列表。

In AngularJS, an Angular module keeps track of controllers, services, and other code. The second argument defines the list of other modules that this module depends upon.

NgModules

import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] }) export class AppModule { }
      
      import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
    

Angular 的模組用 NgModule 裝飾器進行定義,有如下用途:

NgModules, defined with the NgModule decorator, serve the same purpose:

imports: 指定當前模組依賴的其它模組列表

* imports: specifies the list of other modules that this module depends upon

declaration: 用於記錄元件、管道和指令。

* declaration: keeps track of your components, pipes, and directives.

要了解關於模組的更多知識,參閱NgModules

For more information on modules, see NgModules.

控制器註冊

Controller registration

angular .module("movieHunter") .controller("MovieListCtrl", ["movieService", MovieListCtrl]);
      
      angular
  .module("movieHunter")
  .controller("MovieListCtrl",
              ["movieService",
               MovieListCtrl]);
    

在 AngularJS 中,在每個控制器中都有一些程式碼,用於找到合適的 Angular 模組並把該控制器註冊進去。

AngularJS has code in each controller that looks up an appropriate Angular module and registers the controller with that module.

第一個引數是控制器的名稱,第二個引數定義了所有將注入到該控制器的依賴的字串名稱,以及一個到控制器函式的參考。

The first argument is the controller name. The second argument defines the string names of all dependencies injected into this controller, and a reference to the controller function.

元件裝飾器

Component decorator

@Component({ selector: 'app-movie-list', templateUrl: './movie-list.component.html', styleUrls: [ './movie-list.component.css' ], })
      
      @Component({
  selector: 'app-movie-list',
  templateUrl: './movie-list.component.html',
  styleUrls: [ './movie-list.component.css' ],
})
    

Angular 會往元件類別上添加了一個裝飾器,以提供所需的任何元資料。 @Component 裝飾器把該類別宣告為元件,並提供了關於該元件的元資料,比如它的選擇器(或標籤)和範本。

Angular adds a decorator to the component class to provide any required metadata. The @Component decorator declares that the class is a component and provides metadata about that component such as its selector (or tag) and its template.

這就是把範本關聯到程式碼的方式,它定義在元件類別中。

This is how you associate a template with logic, which is defined in the component class.

要了解關於元件的更多資訊,參閱架構概覽中的元件部分。

For more information, see the Components section of the Architecture Overview page.

控制器函式

Controller function

function MovieListCtrl(movieService) { }
      
      function MovieListCtrl(movieService) {
}
    

在 AngularJS 中,你在控制器函式中編寫模型和方法的程式碼。

In AngularJS, you write the code for the model and methods in a controller function.

元件類別

Component class

export class MovieListComponent { }
      
      export class MovieListComponent {
}
    

在 Angular 中,你將建立一個元件類別來容納資料模型和控制方法。使用 TypeScript 的 export 關鍵字匯出該類別,以便可以將此功能匯入 NgModules 中。

In Angular, you create a component class to contain the data model and control methods. Use the TypeScript export keyword to export the class so that the functionality can be imported into NgModules.

要了解關於元件的更多資訊,參閱架構概覽中的元件部分。

For more information, see the Components section of the Architecture Overview page.

依賴注入

Dependency injection

MovieListCtrl.$inject = ['MovieService']; function MovieListCtrl(movieService) { }
      
      MovieListCtrl.$inject = ['MovieService'];
function MovieListCtrl(movieService) {
}
    

在 AngularJS 中,你把所有依賴都作為控制器函式的引數。 這個例子注入了一個 MovieService

In AngularJS, you pass in any dependencies as controller function arguments. This example injects a MovieService.

為了防止在最小化時出現問題,第一個引數明確告訴 Angular 它應該注入一個 MovieService 的實例。

To guard against minification problems, tell Angular explicitly that it should inject an instance of the MovieService in the first parameter.

依賴注入

Dependency injection

constructor(movieService: MovieService) { }
      
      constructor(movieService: MovieService) {
}
    

在 Angular 中,你要把依賴作為元件建構函式的引數傳入。 這個例子注入了一個 MovieService。 即使在最小化之後,第一個引數的 TypeScript 型別也會告訴 Angular 它該注入什麼。

In Angular, you pass in dependencies as arguments to the component class constructor. This example injects a MovieService. The first parameter's TypeScript type tells Angular what to inject, even after minification.

要了解關於依賴注入的更多資訊,參閱架構概覽中的依賴注入部分。

For more information, see the Dependency injection section of the Architecture Overview.

樣式表

Style sheets

樣式表讓你的應用程式看起來更漂亮。 在 AngularJS 中,你要為整個應用程式指定樣式表。 隨著應用程式的不斷成長,為各個部分指定的樣式會被合併,導致無法預計的後果。 在 Angular 中,你仍然要為整個應用程式定義樣式,不過現在也可以把樣式表封裝在特定的元件中。

Style sheets give your application a nice look. In AngularJS, you specify the style sheets for your entire application. As the application grows over time, the styles for the many parts of the application merge, which can cause unexpected results. In Angular, you can still define style sheets for your entire application. But now you can also encapsulate a style sheet within a specific component.

AngularJS

Angular

<link href="styles.css" rel="stylesheet" />
      
      <link href="styles.css" rel="stylesheet" />
    

AngularJS 在 index.htmlhead 區使用 link 標籤來為應用程式定義樣式。

AngularJS, uses a link tag in the head section of the index.html file to define the styles for the application.

樣式配置

Styles configuration

"styles": [ "styles.css" ],
      
      "styles": [
  "styles.css"
],
    

使用 Angular CLI,你可以在 angular.json 檔案中配置全域性樣式。 也可以把副檔名改為 .scss 來使用 sass。

With the Angular CLI, you can configure your global styles in the angular.json file. You can rename the extension to .scss to use sass.

StyleUrls

在 Angular 中,你可以在 @Component 的元資料中使用 stylesstyleUrls 屬性來為一個特定的元件定義樣式表。

In Angular, you can use the styles or styleUrls property of the @Component metadata to define a style sheet for a particular component.

styleUrls: [ './movie-list.component.css' ],
      
      styleUrls: [ './movie-list.component.css' ],
    

這讓你可以為各個元件設定合適的樣式,而不用擔心它洩漏到程式中的其它部分。

This allows you to set appropriate styles for individual components that won’t leak into other parts of the application.