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

Component

一個裝飾器,用於把某個類別標記為 Angular 元件,並為它配置一些元資料,以決定該元件在執行期間該如何處理、實例化和使用。

Decorator that marks a class as an Angular component and provides configuration metadata that determines how the component should be processed, instantiated, and used at runtime.

檢視"說明"...

選項說明
changeDetection?

用於當前元件的變更檢測策略。

The change-detection strategy to use for this component.

viewProviders?

定義一組可注入物件,它們在檢視的各個子節點中可用。參見例子

Defines the set of injectable objects that are visible to its view DOM children. See example.

moduleId?

包含該元件的那個模組的 ID。該元件必須能解析範本和樣式表中使用的相對 URL。 SystemJS 在每個模組中都匯出了 __moduleName 變數。在 CommonJS 中,它可以設定為 module.id

The module ID of the module that contains the component. The component must be able to resolve relative URLs for templates and styles. SystemJS exposes the __moduleName variable within each module. In CommonJS, this can be set to module.id.

templateUrl?

Angular 元件範本檔案的 URL。如果提供了它,就不要再用 template 來提供內聯範本了。

The relative path or absolute URL of a template file for an Angular component. If provided, do not supply an inline template using template.

template?

Angular 元件的內聯範本。如果提供了它,就不要再用 templateUrl 提供範本了。

An inline template for an Angular component. If provided, do not supply a template file using templateUrl.

styleUrls?

一個或多個 URL,指向包含本元件 CSS 樣式表的檔案。

One or more relative paths or absolute URLs for files containing CSS stylesheets to use in this component.

styles?

本元件用到的一個或多個內聯 CSS 樣式。

One or more inline CSS stylesheets to use in this component.

animations?

一個或多個動畫 trigger() 呼叫,包含一些 state()transition() 定義。 參見動畫和相關的 API 文件。

One or more animation trigger() calls, containing state() and transition() definitions. See the Animations guide and animations API documentation.

encapsulation?

供範本和 CSS 樣式使用的樣式封裝策略。取值為:

An encapsulation policy for the template and CSS styles. One of:

interpolation?

改寫預設的插值表示式起止分界符({{}})。

Overrides the default interpolation start and end delimiters ({{ and }}).

entryComponents?

一個元件的集合,它應該和當前元件一起編譯。對於這裡列出的每個元件,Angular 都會建立一個 ComponentFactory並儲存進 ComponentFactoryResolver中。

A set of components that should be compiled along with this component. For each component listed here, Angular creates a ComponentFactoryand stores it in the ComponentFactoryResolver.

preserveWhitespaces?

true 則保留,為 false 則從編譯後的範本中移除可能多餘的空白字元。 空白字元就是指那些能在 JavaScript 正則表示式中匹配 \s 的字元。預設為 false,除非透過編譯器選項改寫了它。

True to preserve or false to remove potentially superfluous whitespace characters from the compiled template. Whitespace characters are those matching the \s character class in JavaScript regular expressions. Default is false, unless overridden in compiler options.

繼承自 Directive 裝飾器

選項說明
selector?

這個 CSS 選擇器用於在範本中標記出該指令,並觸發該指令的實例化。

The CSS selector that identifies this directive in a template and triggers instantiation of the directive.

inputs?

列舉某個指令的一組可供資料繫結的輸入屬性

Enumerates the set of data-bound input properties for a directive

outputs?

列舉一組可供事件繫結的輸出屬性。

Enumerates the set of event-bound output properties.

providers?

一組依賴注入令牌,它允許 DI 系統為這個指令或元件提供依賴。

Configures the injector of this directive or component with a token that maps to a provider of a dependency.

exportAs?

定義一個名字,用於在範本中把該指令賦值給一個變數。

Defines the name that can be used in the template to assign this directive to a variable.

queries?

配置一些查詢,它們將被注入到該指令中。

Configures the queries that will be injected into the directive.

host?

使用一組鍵-值對,把類別的屬性對映到宿主元素的繫結(Property、Attribute 和事件)。

Maps class properties to host element bindings for properties, attributes, and events, using a set of key-value pairs.

jit?

如果存在,則該指令/元件將被 AOT 編譯器忽略。它會保留在發佈程式碼中,並且 JIT 編譯器會嘗試在執行時在瀏覽器中對其進行編譯。為了確保其行為正確,該應用程式必須匯入 @angular/compiler

When present, this directive/component is ignored by the AOT compiler. It remains in distributed code, and the JIT compiler attempts to compile it at run time, in the browser. To ensure the correct behavior, the app must import @angular/compiler.

說明

元件是 Angular 應用中最基本的 UI 構成要素。Angular 應用中包含一棵元件樹。

Components are the most basic UI building block of an Angular app. An Angular app contains a tree of Angular components.

Angular 的元件是指令的一個子集,它總是有一個與之關聯的範本。 和其它指令不同,範本中的每個元素只能具有一個元件實例。

Angular components are a subset of directives, always associated with a template. Unlike other directives, only one component can be instantiated for a given element in a template.

元件必須從屬於某個 NgModule 才能被其它元件或應用使用。 要想讓它成為某個 NgModule 中的一員,請把它列在 @NgModule 元資料的 declarations 欄位中。

A component must belong to an NgModule in order for it to be available to another component or application. To make it a member of an NgModule, list it in the declarations field of the NgModule metadata.

注意,除了這些用來對指令進行配置的選項之外,你還可以透過實現生命週期鉤子來控制組件的執行期行為。 要了解更多,參見 生命週期鉤子 章。

Note that, in addition to these options for configuring a directive, you can control a component's runtime behavior by implementing life-cycle hooks. For more information, see the Lifecycle Hooks guide.

Further information available in the Usage Notes...

選項

用於當前元件的變更檢測策略。

The change-detection strategy to use for this component.

      
      changeDetection?: ChangeDetectionStrategy
    

當元件實例化之後,Angular 就會建立一個變更檢測器,它負責傳播元件各個繫結值的變化。 該策略是下列值之一:

When a component is instantiated, Angular creates a change detector, which is responsible for propagating the component's bindings. The strategy is one of:

定義一組可注入物件,它們在檢視的各個子節點中可用。參見例子

Defines the set of injectable objects that are visible to its view DOM children. See example.

      
      viewProviders?: Provider[]
    

包含該元件的那個模組的 ID。該元件必須能解析範本和樣式表中使用的相對 URL。 SystemJS 在每個模組中都匯出了 __moduleName 變數。在 CommonJS 中,它可以設定為 module.id

The module ID of the module that contains the component. The component must be able to resolve relative URLs for templates and styles. SystemJS exposes the __moduleName variable within each module. In CommonJS, this can be set to module.id.

      
      moduleId?: string
    

Angular 元件範本檔案的 URL。如果提供了它,就不要再用 template 來提供內聯範本了。

The relative path or absolute URL of a template file for an Angular component. If provided, do not supply an inline template using template.

      
      templateUrl?: string
    

Angular 元件的內聯範本。如果提供了它,就不要再用 templateUrl 提供範本了。

An inline template for an Angular component. If provided, do not supply a template file using templateUrl.

      
      template?: string
    

一個或多個 URL,指向包含本元件 CSS 樣式表的檔案。

One or more relative paths or absolute URLs for files containing CSS stylesheets to use in this component.

      
      styleUrls?: string[]
    

本元件用到的一個或多個內聯 CSS 樣式。

One or more inline CSS stylesheets to use in this component.

      
      styles?: string[]
    

一個或多個動畫 trigger() 呼叫,包含一些 state()transition() 定義。 參見動畫和相關的 API 文件。

One or more animation trigger() calls, containing state() and transition() definitions. See the Animations guide and animations API documentation.

      
      animations?: any[]
    

供範本和 CSS 樣式使用的樣式封裝策略。取值為:

An encapsulation policy for the template and CSS styles. One of:

      
      encapsulation?: ViewEncapsulation
    

如果沒有提供,該值就會從 CompilerOptions 中獲取它。預設的編譯器選項是 ViewEncapsulation.Emulated

If not supplied, the value is taken from CompilerOptions. The default compiler option is ViewEncapsulation.Emulated.

如果該策略設定為 ViewEncapsulation.Emulated,並且該元件沒有指定 stylesstyleUrls,就會自動切換到 ViewEncapsulation.None

If the policy is set to ViewEncapsulation.Emulated and the component has no styles or styleUrls specified, the policy is automatically switched to ViewEncapsulation.None.

改寫預設的插值表示式起止分界符({{}})。

Overrides the default interpolation start and end delimiters ({{ and }}).

      
      interpolation?: [string, string]
    

一個元件的集合,它應該和當前元件一起編譯。對於這裡列出的每個元件,Angular 都會建立一個 ComponentFactory並儲存進 ComponentFactoryResolver中。

A set of components that should be compiled along with this component. For each component listed here, Angular creates a ComponentFactoryand stores it in the ComponentFactoryResolver.

      
      entryComponents?: Array<Type<any> | any[]>
    

true 則保留,為 false 則從編譯後的範本中移除可能多餘的空白字元。 空白字元就是指那些能在 JavaScript 正則表示式中匹配 \s 的字元。預設為 false,除非透過編譯器選項改寫了它。

True to preserve or false to remove potentially superfluous whitespace characters from the compiled template. Whitespace characters are those matching the \s character class in JavaScript regular expressions. Default is false, unless overridden in compiler options.

      
      preserveWhitespaces?: boolean
    

使用說明

設定元件的輸入屬性

Setting component inputs

下免得例子建立了一個帶有兩個資料繫結屬性的元件,它是透過 inputs 值來指定的。

The following example creates a component with two data-bound properties, specified by the inputs value.

      
      @Component({
  selector: 'app-bank-account',
  inputs: ['bankName', 'id: account-id'],
  template: `
    Bank Name: {{ bankName }}
    Account Id: {{ id }}
  `
})
export class BankAccountComponent {
  bankName: string|null = null;
  id: string|null = null;

  // this property is not bound, and won't be automatically updated by Angular
  normalizedBankName: string|null = null;
}

@Component({
  selector: 'app-my-input',
  template: `
    <app-bank-account
      bankName="RBC"
      account-id="4747">
    </app-bank-account>
  `
})
export class MyInputComponent {
}
    

設定元件的輸出屬性

Setting component outputs

下面的例子展示了兩個事件發生器,它們定時發出事件。一個每隔一秒發出一個輸出事件,另一個則隔五秒。

The following example shows two event emitters that emit on an interval. One emits an output every second, while the other emits every five seconds.

      
      @Directive({selector: 'app-interval-dir', outputs: ['everySecond', 'fiveSecs: everyFiveSeconds']})
export class IntervalDirComponent {
  everySecond = new EventEmitter<string>();
  fiveSecs = new EventEmitter<string>();

  constructor() {
    setInterval(() => this.everySecond.emit('event'), 1000);
    setInterval(() => this.fiveSecs.emit('event'), 5000);
  }
}

@Component({
  selector: 'app-my-output',
  template: `
    <app-interval-dir
      (everySecond)="onEverySecond()"
      (everyFiveSeconds)="onEveryFiveSeconds()">
    </app-interval-dir>
  `
})
export class MyOutputComponent {
  onEverySecond() {
    console.log('second');
  }
  onEveryFiveSeconds() {
    console.log('five seconds');
  }
}
    

使用檢視提供者注入一個類別

Injecting a class with a view provider

下面的例子示範瞭如何在元件元資料中使用檢視提供者來把一個類別注入到元件中:

The following simple example injects a class into a component using the view provider specified in component metadata:

      
      class Greeter {
   greet(name:string) {
     return 'Hello ' + name + '!';
   }
}

@Directive({
  selector: 'needs-greeter'
})
class NeedsGreeter {
  greeter:Greeter;

  constructor(greeter:Greeter) {
    this.greeter = greeter;
  }
}

@Component({
  selector: 'greet',
  viewProviders: [
    Greeter
  ],
  template: `<needs-greeter></needs-greeter>`
})
class HelloWorld {
}
    

Preserving whitespace

Removing whitespace can greatly reduce AOT-generated code size and speed up view creation. As of Angular 6, the default for preserveWhitespaces is false (whitespace is removed). To change the default setting for all components in your application, set the preserveWhitespaces option of the AOT compiler.

By default, the AOT compiler removes whitespace characters as follows:

  • Trims all whitespaces at the beginning and the end of a template.
  • Removes whitespace-only text nodes. For example,
      
      <button>Action 1</button>  <button>Action 2</button>
    

becomes:

      
      <button>Action 1</button><button>Action 2</button>
    
  • Replaces a series of whitespace characters in text nodes with a single space. For example, <span>\n some text\n</span> becomes <span> some text </span>.
  • Does NOT alter text nodes inside HTML tags such as <pre> or <textarea>, where whitespace characters are significant.

Note that these transformations can influence DOM nodes layout, although impact should be minimal.

You can override the default behavior to preserve whitespace characters in certain fragments of a template. For example, you can exclude an entire DOM sub-tree by using the ngPreserveWhitespaces attribute:

      
      <div ngPreserveWhitespaces>
    whitespaces are preserved here
    <span>    and here </span>
</div>
    

You can force a single space to be preserved in a text node by using &ngsp;, which is replaced with a space character by Angular's template compiler:

      
      <a>Spaces</a>&ngsp;<a>between</a>&ngsp;<a>links.</a>
<!-- compiled to be equivalent to:
 <a>Spaces</a> <a>between</a> <a>links.</a>  -->
    

Note that sequences of &ngsp; are still collapsed to just one space character when the preserveWhitespaces option is set to false.

      
      <a>before</a>&ngsp;&ngsp;&ngsp;<a>after</a>
<!-- compiled to be equivalent to:
 <a>before</a> <a>after</a> -->
    

To preserve sequences of whitespace characters, use the ngPreserveWhitespaces attribute.