Ng2Component | @uirouter/angular
Options
Menu

Interface Ng2Component

The shape of a controller for a view (and/or component), defining the controller callbacks.

A UI-Router view has an Angular Component (see Ng2ViewDeclaration.component). The Component may define component-level hooks which UI-Router will call at the appropriate times. These callbacks are similar to Transition Hooks (IHookRegistry), but are only called if the view/component is currently active.

This interface defines the UI-Router component callbacks.

Hierarchy

  • Component
    • Ng2Component

Index

Properties

Component: ComponentDecorator

Component decorator and metadata.

Component decorator and metadata.

stable
annotation
animations: any[]

Animations are defined on components via an animation-like DSL. This DSL approach to describing animations allows for a flexibility that both benefits developers and the framework.

Animations are defined on components via an animation-like DSL. This DSL approach to describing animations allows for a flexibility that both benefits developers and the framework.

Animations work by listening on state changes that occur on an element within the template. When a state change occurs, Angular can then take advantage and animate the arc in between. This works similar to how CSS transitions work, however, by having a programmatic DSL, animations are not limited to environments that are DOM-specific. (Angular can also perform optimizations behind the scenes to make animations more performant.)

For animations to be available for use, animation state changes are placed within {@link trigger animation triggers} which are housed inside of the animations annotation metadata. Within a trigger both {@link state state} and {@link transition transition} entries can be placed.

```typescript

component({

selector: 'animation-cmp', templateUrl: 'animation-cmp.html', animations: [ // this here is our animation trigger that // will contain our state change animations. trigger('myTriggerName', [ // the styles defined for the on and off // states declared below are persisted on the // element once the animation completes. state('on', style({ opacity: 1 }), state('off', style({ opacity: 0 }),

  // this here is our animation that kicks off when
  // this state change jump is true
  transition('on => off', [
    animate("1s")
  ])
])

] })


As depicted in the code above, a group of related animation states are all contained within
an animation `trigger` (the code example above called the trigger `myTriggerName`).
When a trigger is created then it can be bound onto an element within the component's
template via a property prefixed by an `@` symbol followed by trigger name and an expression
that
is used to determine the state value for that trigger.

```html
<!-- animation-cmp.html -->
<div @myTriggerName="expression">...</div>

For state changes to be executed, the expression value must change value from its existing value to something that we have set an animation to animate on (in the example above we are listening to a change of state between on and off). The expression value attached to the trigger must be something that can be evaluated with the template/component context.

DSL Animation Functions

Please visit each of the animation DSL functions listed below to gain a better understanding of how and why they are used for crafting animations in Angular:

  • {@link trigger trigger()}
  • {@link state state()}
  • {@link transition transition()}
  • {@link group group()}
  • {@link sequence sequence()}
  • {@link style style()}
  • {@link animate animate()}
  • {@link keyframes keyframes()}
changeDetection: ChangeDetectionStrategy.OnPush | ChangeDetectionStrategy.Default

Defines the used change detection strategy.

Defines the used change detection strategy.

When a component is instantiated, Angular creates a change detector, which is responsible for propagating the component's bindings.

The changeDetection property defines, whether the change detection will be checked every time or only when the component tells it to do so.

encapsulation: ViewEncapsulation.Emulated | ViewEncapsulation.Native | ViewEncapsulation.None

Specifies how the template and the styles should be encapsulated:

  • {@link ViewEncapsulation#Native ViewEncapsulation.Native} to use shadow roots - only works if natively available on the platform,
  • {@link ViewEncapsulation#Emulated ViewEncapsulation.Emulated} to use shimmed CSS that emulates the native behavior,
  • {@link ViewEncapsulation#None ViewEncapsulation.None} to use global CSS without any encapsulation.

Specifies how the template and the styles should be encapsulated:

  • {@link ViewEncapsulation#Native ViewEncapsulation.Native} to use shadow roots - only works if natively available on the platform,
  • {@link ViewEncapsulation#Emulated ViewEncapsulation.Emulated} to use shimmed CSS that emulates the native behavior,
  • {@link ViewEncapsulation#None ViewEncapsulation.None} to use global CSS without any encapsulation.

When no encapsulation is defined for the component, the default value from the {@link CompilerOptions} is used. The default is ViewEncapsulation.Emulated}. Provide a new CompilerOptions to override this value.

If the encapsulation is set to ViewEncapsulation.Emulated and the component has no styles nor styleUrls the encapsulation will automatically be switched to ViewEncapsulation.None.

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

Defines the components that should be compiled as well when this component is defined. For each components listed here, Angular will create a {@link ComponentFactory} and store it in the {@link ComponentFactoryResolver}.

Defines the components that should be compiled as well when this component is defined. For each components listed here, Angular will create a {@link ComponentFactory} and store it in the {@link ComponentFactoryResolver}.

exportAs: string

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

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

Simple Example

```

directive({

selector: 'child-dir', exportAs: 'child' }) class ChildDir { }

component({

selector: 'main', template: <child-dir #c="child"></child-dir> }) class MainComponent { }

```

host: object

Specify the events, actions, properties and attributes related to the host element.

Specify the events, actions, properties and attributes related to the host element.

Host Listeners

Specifies which DOM events a directive listens to via a set of (event) to method key-value pairs:

  • event: the DOM event that the directive listens to.
  • statement: the statement to execute when the event occurs. If the evaluation of the statement returns false, then preventDefaultis applied on the DOM event.

To listen to global events, a target must be added to the event name. The target can be window, document or body.

When writing a directive event binding, you can also refer to the $event local variable.

Example (live demo)

The following example declares a directive that attaches a click listener to the button and counts clicks.

```typescript

directive({

selector: 'button[counting]', host: { '(click)': 'onClick($event.target)' } }) class CountClicks { numberOfClicks = 0;

onClick(btn) { console.log("button", btn, "number of clicks:", this.numberOfClicks++); } }

component({

selector: 'app', template: <button counting>Increment</button> }) class App {} ```

Host Property Bindings

Specifies which DOM properties a directive updates.

Angular automatically checks host property bindings during change detection. If a binding changes, it will update the host element of the directive.

Example (live demo)

The following example creates a directive that sets the valid and invalid classes on the DOM element that has ngModel directive on it.

```typescript

directive({

selector: '[ngModel]', host: { '[class.valid]': 'valid', '[class.invalid]': 'invalid' } }) class NgModelStatus { constructor(public control:NgModel) {} get valid { return this.control.valid; } get invalid { return this.control.invalid; } }

component({

selector: 'app', template: <input [(ngModel)]="prop"> }) class App { prop; } ```

Attributes

Specifies static attributes that should be propagated to a host element.

Example

In this example using my-button directive (ex.: <div my-button></div>) on a host element (here: <div> ) will ensure that this element will get the "button" role.

```typescript

directive({

selector: '[my-button]', host: { 'role': 'button' } }) class MyButton { } ```

Type declaration

  • [key: string]: string
inputs: string[]

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

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

Angular automatically updates input properties during change detection.

The inputs property defines a set of directiveProperty to bindingProperty configuration:

  • directiveProperty specifies the component property where the value is written.
  • bindingProperty specifies the DOM property where the value is read from.

When bindingProperty is not provided, it is assumed to be equal to directiveProperty.

Example (live demo)

The following example creates a component with two data-bound properties.

```typescript

component({

selector: 'bank-account', inputs: ['bankName', 'id: account-id'], template: Bank Name: Account Id: }) class BankAccount { bankName: string; id: string;

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

component({

selector: 'app', template: <bank-account bank-name="RBC" account-id="4747"></bank-account> }) class App {} ```

interpolation: [string, string]

Overrides the default encapsulation start and end delimiters (respectively )

Overrides the default encapsulation start and end delimiters (respectively )

moduleId: string

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

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

Simple Example

```

directive({

selector: 'someDir', moduleId: module.id }) class SomeDir { }

```

outputs: string[]

Enumerates the set of event-bound output properties.

Enumerates the set of event-bound output properties.

When an output property emits an event, an event handler attached to that event the template is invoked.

The outputs property defines a set of directiveProperty to bindingProperty configuration:

  • directiveProperty specifies the component property that emits events.
  • bindingProperty specifies the DOM property the event handler is attached to.

Example (live demo)

```typescript

directive({

selector: 'interval-dir', outputs: ['everySecond', 'five5Secs: everyFiveSeconds'] }) class IntervalDir { everySecond = new EventEmitter(); five5Secs = new EventEmitter();

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

component({

selector: 'app', template: <interval-dir (everySecond)="everySecond()" (everyFiveSeconds)="everyFiveSeconds()"> </interval-dir> }) class App { everySecond() { console.log('second'); } everyFiveSeconds() { console.log('five seconds'); } } ```

preserveWhitespaces: boolean

If {@link Component#preserveWhitespaces Component.preserveWhitespaces} is set to false potentially superfluous whitespace characters (ones matching the \s character class in JavaScript regular expressions) will be removed from a compiled template. This can greatly reduce AOT-generated code size as well as speed up view creation.

If {@link Component#preserveWhitespaces Component.preserveWhitespaces} is set to false potentially superfluous whitespace characters (ones matching the \s character class in JavaScript regular expressions) will be removed from a compiled template. This can greatly reduce AOT-generated code size as well as speed up view creation.

Current implementation works according to the following rules:

  • all whitespaces at the beginning and the end of a template are removed (trimmed);
  • text nodes consisting of whitespaces only are removed (ex.: <button>Action 1</button> <button>Action 2</button> will be converted to <button>Action 1</button><button>Action 2</button> (no whitespaces between buttons);
  • series of whitespaces in text nodes are replaced with one space (ex.: <span>\n some text\n</span> will be converted to <span> some text </span>);
  • text nodes are left as-is inside HTML tags where whitespaces are significant (ex. <pre>, <textarea>).

Described transformations can (potentially) influence DOM nodes layout so the preserveWhitespaces option is true be default (no whitespace removal). In Angular 5 you need to opt-in for whitespace removal (but we might revisit the default setting in Angular 6 or later). If you want to change the default setting for all components in your application you can use the preserveWhitespaces option of the AOT compiler.

Even if you decide to opt-in for whitespace removal there are ways of preserving whitespaces in certain fragments of a template. You can either exclude entire DOM sub-tree by using the ngPreserveWhitespaces attribute, ex.:

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

Alternatively you can force a space to be preserved in a text node by using the &ngsp; pseudo-entity. &ngsp; will be replaced with a space character by Angular's template compiler, ex.:

<a>Spaces</a>&ngsp;<a>between</a>&ngsp;<a>links.</a>

will be compiled to the equivalent of:

<a>Spaces</a> <a>between</a> <a>links.</a>

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

<a>before</a>&ngsp;&ngsp;&ngsp;<a>after</a>

would be equivalent to:

<a>before</a> <a>after</a>

The &ngsp; pseudo-entity is useful for forcing presence of one space (a text node having &ngsp; pseudo-entities will never be removed), but it is not meant to mark sequences of whitespace characters. The previously described ngPreserveWhitespaces attribute is more useful for preserving sequences of whitespace characters.

providers: Provider[]

Defines the set of injectable objects that are visible to a Directive and its light DOM children.

Defines the set of injectable objects that are visible to a Directive and its light DOM children.

Simple Example

Here is an example of a class that can be injected:

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

directive({

selector: 'greet', providers: [ Greeter ] }) class HelloWorld { greeter:Greeter;

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

queries: object

Configures the queries that will be injected into the directive.

Configures the queries that will be injected into the directive.

Content queries are set before the ngAfterContentInit callback is called. View queries are set before the ngAfterViewInit callback is called.

Example

```

component({

selector: 'someDir', queries: { contentChildren: new ContentChildren(ChildDirective), viewChildren: new ViewChildren(ChildDirective) }, template: '' }) class SomeDir { contentChildren: QueryList, viewChildren: QueryList

ngAfterContentInit() { // contentChildren is set }

ngAfterViewInit() { // viewChildren is set } } ```

Type declaration

  • [key: string]: any
selector: string

The CSS selector that triggers the instantiation of a directive.

The CSS selector that triggers the instantiation of a directive.

Angular only allows directives to trigger on CSS selectors that do not cross element boundaries.

selector may be declared as one of the following:

  • element-name: select by element name.
  • .class: select by class name.
  • [attribute]: select by attribute name.
  • [attribute=value]: select by attribute name and value.
  • :not(sub_selector): select only if the element does not match the sub_selector.
  • selector1, selector2: select if either selector1 or selector2 matches.

Example

Suppose we have a directive with an input[type=text] selector.

And the following HTML:

<form>
  <input type="text">
  <input type="radio">
<form>

The directive would only be instantiated on the <input type="text"> element.

styleUrls: string[]

Specifies stylesheet URLs for an Angular component.

Specifies stylesheet URLs for an Angular component.

styles: string[]

Specifies inline stylesheets for an Angular component.

Specifies inline stylesheets for an Angular component.

template: string

Specifies an inline template for an Angular component.

Specifies an inline template for an Angular component.

Only one of templateUrl or template can be defined per Component.

templateUrl: string

Specifies a template URL for an Angular component.

Specifies a template URL for an Angular component.

Only one of templateUrl or template can be defined per View.

viewProviders: Provider[]

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

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

Simple Example

Here is an example of a class that can be injected:

``` 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 { }

```

Methods

  • uiCanExit(newTransition?: Transition): HookResult
  • This callback is called when the a routed component's state is about to be exited.

  • This callback is called when the a routed component's state is about to be exited.

    The callback can be used to cancel or alter the new Transition that would otherwise exit the component's state.

    This callback is used to inform a view that it is about to be exited, due to a new Transition. The callback can ask for user confirmation, and cancel or alter the new Transition. The callback should return a value, or a promise for a value. If a promise is returned, the new Transition waits until the promise settles.

    Called when:

    • The component is still active inside a ui-view
    • A new Transition is about to run
    • The new Transition will exit the view's state

    Called with:

    • The Transition that is about to exit the component's state

    Example:

    ```js

    component({

    template: '' }) class MyComponent { dirty = true;

    constructor(public confirmService: confirmService) {

    }

    uiCanExit(newTransition: Transition) { if (this.dirty && newTransition.to() !== 'logout') { return this.confirmService.confirm("Exit without saving changes?"); } } } ```

    Parameters

    • newTransition: Optional  Transition

    Returns HookResult

    :

    a hook result which may cancel or alter the pending Transition (see HookResult)


Generated using TypeDoc