填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写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 encapsulation 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

如果为 true,则该指令/组件将会被 AOT 编译器忽略,始终使用 JIT 编译。

If true, this directive/component will be skipped by the AOT compiler and so will always be compiled using JIT.

说明

组件是 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 per an 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.

选项

用于当前组件的变更检测策略。

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
      
      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
      
      templateUrl: string
    

Angular 组件的内联模板。如果提供了它,就不要再用 templateUrl 提供模板了。

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

template: string
      
      template: string
    

一个或多个 URL,指向包含本组件 CSS 样式表的文件。

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

styleUrls: string[]
      
      styleUrls: string[]
    

本组件用到的一个或多个内联 CSS 样式。

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

styles: string[]
      
      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[]
      
      animations: any[]
    

供模板和 CSS 样式使用的样式封装策略。取值为:

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

encapsulation: ViewEncapsulation
      
      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 encapsulation start and end delimiters ({{ and }})

interpolation: [string, string]
      
      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[]>
      
      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 { }
      
      @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'); } }
      
      @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 { }
      
      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>
      
      <button>Action 1</button>  <button>Action 2</button>
    

becomes:

<button>Action 1</button><button>Action 2</button>
      
      <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>
      
      <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>
      
      <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>Spaces</a> <a>between</a> <a>links.</a>
      
      <a>before</a>&ngsp;&ngsp;&ngsp;<a>after</a>
<!-->compiled to be equivalent to:</>
 <a>Spaces</a> <a>between</a> <a>links.</a>
    

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