Help Angular by taking a 1 minute survey!Go to surveyHome

Component

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.

See more...

OptionDescription
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

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

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

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

styleUrls

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

styles

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

animations

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

encapsulation

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

interpolation

Overrides the default encapsulation start and end delimiters ({{ and }})

entryComponents

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

preserveWhitespaces

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.

Inherited from Directive decorator

OptionDescription
selector

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

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

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

jit

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

Description

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

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.

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.

Options

The change-detection strategy to use for this component.

      
      changeDetection: ChangeDetectionStrategy
    

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[]
    

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
    

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
    

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

template: string
      
      template: string
    

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

styleUrls: string[]
      
      styleUrls: string[]
    

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

styles: string[]
      
      styles: string[]
    

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

animations: any[]
      
      animations: any[]
    

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

encapsulation: ViewEncapsulation
      
      encapsulation: ViewEncapsulation
    

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

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]
    

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

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

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
    

Usage notes

Setting component 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 { }
      
      
  1. @Component({
  2. selector: 'app-bank-account',
  3. inputs: ['bankName', 'id: account-id'],
  4. template: `
  5. Bank Name: {{ bankName }}
  6. Account Id: {{ id }}
  7. `
  8. })
  9. export class BankAccountComponent {
  10. bankName: string|null = null;
  11. id: string|null = null;
  12.  
  13. // this property is not bound, and won't be automatically updated by Angular
  14. normalizedBankName: string|null = null;
  15. }
  16.  
  17. @Component({
  18. selector: 'app-my-input',
  19. template: `
  20. <app-bank-account
  21. bankName="RBC"
  22. account-id="4747">
  23. </app-bank-account>
  24. `
  25. })
  26. export class MyInputComponent {
  27. }

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'); } }
      
      
  1. @Directive({selector: 'app-interval-dir', outputs: ['everySecond', 'fiveSecs: everyFiveSeconds']})
  2. export class IntervalDirComponent {
  3. everySecond = new EventEmitter<string>();
  4. fiveSecs = new EventEmitter<string>();
  5.  
  6. constructor() {
  7. setInterval(() => this.everySecond.emit('event'), 1000);
  8. setInterval(() => this.fiveSecs.emit('event'), 5000);
  9. }
  10. }
  11.  
  12. @Component({
  13. selector: 'app-my-output',
  14. template: `
  15. <app-interval-dir
  16. (everySecond)="onEverySecond()"
  17. (everyFiveSeconds)="onEveryFiveSeconds()">
  18. </app-interval-dir>
  19. `
  20. })
  21. export class MyOutputComponent {
  22. onEverySecond() { console.log('second'); }
  23. onEveryFiveSeconds() { console.log('five seconds'); }
  24. }

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 { }
      
      
  1. class Greeter {
  2. greet(name:string) {
  3. return 'Hello ' + name + '!';
  4. }
  5. }
  6.  
  7. @Directive({
  8. selector: 'needs-greeter'
  9. })
  10. class NeedsGreeter {
  11. greeter:Greeter;
  12.  
  13. constructor(greeter:Greeter) {
  14. this.greeter = greeter;
  15. }
  16. }
  17.  
  18. @Component({
  19. selector: 'greet',
  20. viewProviders: [
  21. Greeter
  22. ],
  23. template: `<needs-greeter></needs-greeter>`
  24. })
  25. class HelloWorld {
  26. }

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.