Ng2StateDeclaration | UI-Router
Options
All
  • Public
  • Public/Protected
  • All
Menu

Interface Ng2StateDeclaration

The StateDeclaration object is used to define a state or nested state. It should be registered with the StateRegistry.

example

import {FoldersComponent} from "./folders";

// StateDeclaration object
var foldersState = {
  name: 'folders',
  url: '/folders',
  component: FoldersComponent,
  resolve: {
    allfolders: function(FolderService) {
      return FolderService.list();
    }
  }
}

Hierarchy

Index

Properties

abstract: boolean

abstract state indicator

abstract state indicator

An abstract state can never be directly activated. Use an abstract state to provide inherited properties (url, resolve, data, etc) to children states.

bindings: object

An object which maps resolve keys to component bindings.

An object which maps resolve keys to component bindings.

A property of Ng2StateDeclaration or Ng2ViewDeclaration:

When using a component declaration (component: MyComponent), each input binding for the component is supplied data from a resolve of the same name, by default. You may supply data from a different resolve name by mapping it here.

Each key in this object is the name of one of the component's input bindings. Each value is the name of the resolve that should be provided to that binding.

Any component bindings that are omitted from this map get the default behavior of mapping to a resolve of the same name.

example

$stateProvider.state('foo', {
  resolve: {
    foo: function(FooService) { return FooService.get(); },
    bar: function(BarService) { return BarService.get(); }
  },
  component: 'Baz',
  // The component's `baz` binding gets data from the `bar` resolve
  // The component's `foo` binding gets data from the `foo` resolve (default behavior)
  bindings: {
    baz: 'bar'
  }
});

app.component('Baz', {
  templateUrl: 'baz.html',
  controller: 'BazController',
  bindings: {
    foo: '<', // foo binding
    baz: '<'  // baz binding
  }
});

Type declaration

  • [key: string]: string
component: Type<any>

The Component class to use for this view.

The Component class to use for this view.

A property of Ng2StateDeclaration or Ng2ViewDeclaration:

The component class which will be used for this view.

example

.state('profile', {
  // Use the <my-profile></my-profile> component for the Unnamed view
  component: MyProfileComponent,
}

.state('messages', {
  // use the <nav-bar></nav-bar> component for the view named 'header'
  // use the <message-list></message-list> component for the view named 'content'
  views: {
    header: { component: NavBar },
    content: { component: MessageList }
  }
}

// Named views shorthand:
// Inside a "views:" block, a Component class (NavBar) is shorthand for { component: NavBar }
.state('contacts', {
  // use the <nav-bar></nav-bar> component for the view named 'header'
  // use the <contact-list></contact-list> component for the view named 'content'
  views: {
    header: NavBar,
    content: ContactList
  }
}

Accessing Resolve Data

The component can access the Transition's Ng2StateDeclaration.resolve data in one of two ways:

1) Using Dependency Injection in the component constructor

(using Typescript)

class MyComponent {
  constructor(@Inject("myResolveData") public resolveValueA, resolveValueB: public SomeClass) {
  }
}

(using ES6/7/babel)

class MyComponent {
  static get parameters() {
    return [["myResolveData"], [MyResolveClass]];
  }
  constructor(resolveValueA, resolveValueB) {
    this.resolveValueA = resolveValueA;
    this.resolveValueB = resolveValueB;
  }
}

See also: https://github.com/shuhei/babel-plugin-angular2-annotations

2) Using a component input

Note: To bind a resolve to a component input, the resolves must provide: a string value

```js

component

() { inputs: ['resolveValueA'] } class MyComponent { myResolveValueA; @Input() resolveValueB; @Input("resolveValueC") resolveValueC;

constructor() { } } ```

data: any

An inherited property to store state data

An inherited property to store state data

This is a spot for you to store inherited state metadata. Child states' data object will prototypally inherit from their parent state.

This is a good spot to put metadata such as requiresAuth.

Note: because prototypal inheritance is used, changes to parent data objects reflect in the child data objects. Care should be taken if you are using hasOwnProperty on the data object. Properties from parent objects will return false for hasOwnProperty.

lazyLoad: function

A function which lazy loads the state definition (and child state definitions)

A function which lazy loads the state definition (and child state definitions)

A state which has a lazyLoad function is treated as a temporary placeholder for a state definition that will be lazy loaded some time in the future. These temporary placeholder states are called "Future States".

lazyLoad:

A future state's lazyLoad function should return a Promise to lazy load the code for one or more lazy loaded StateDeclaration objects.

If the promise resolves to an object with a states: [] array, the lazy loaded states will be registered with the StateRegistry. Generally, of the lazy loaded states should have the same name as the future state; then it will replace the future state placeholder in the registry.

In any case, when the promise successfully resolves, the placeholder Future State will be deregistered.

url

A future state's url property acts as a wildcard.

UI-Router matches all paths that begin with the url. It effectively appends .* to the internal regular expression.

name

A future state's name property acts as a wildcard.

It matches any state name that starts with the name. UI-Router effectively matches the future state using a .** Glob appended to the name.

example

states.js


// This child state is a lazy loaded future state
// The `lazyLoad` function loads the final state definition
{
  name: 'parent.child',
  url: '/child',
  lazyLoad: () => System.import('./child.state.js')
}

child.state.js

This file is lazy loaded. It exports an array of states.

import {ChildComponent} from "./child.component.js";

let childState = {
  // the name should match the future state
  name: 'parent.child',
  url: '/child/:childId',
  params: {
    id: "default"
  },
  resolve: {
    childData: ($transition$, ChildService) =>
        ChildService.get($transition$.params().childId)
  }
};

// This array of states will be registered by the lazyLoad hook
let result = {
  states: [ childState ]
};

export default result;
param

the Transition that is activating the future state

returns

a Promise to load the states. Optionally, if the promise resolves to a LazyLoadResult, the states will be registered with the StateRegistry.

Type declaration

name: string

The state name

The state name

A unique state name, e.g. "home", "about", "contacts". To create a parent/child state use a dot, e.g. "about.sales", "home.newest".

Note: States require unique names. If you omit this property, you must provide the state name when you register it with the $stateProvider.

onEnter: TransitionStateHookFn

A Transition Hook called with the state is being entered. See: IHookRegistry.onEnter

A Transition Hook called with the state is being entered. See: IHookRegistry.onEnter

example

.state({
  name: 'mystate',
  onEnter: function(trans, state) {
    console.log("Entering " + state.name);
  }
});

Note: The above onEnter on the state declaration is effectively sugar for: ``` transitionService.onEnter({ entering: 'mystate' }, function(trans, state) { console.log("Entering " + state.name); });

onExit: TransitionStateHookFn

A Transition Hook called with the state is being exited. See: IHookRegistry.onExit

A Transition Hook called with the state is being exited. See: IHookRegistry.onExit

example

.state({
  name: 'mystate',
  onExit: function(trans, state) {
    console.log("Leaving " + state.name);
  }
});

Note: The above onRetain on the state declaration is effectively sugar for: ``` transitionService.onExit({ exiting: 'mystate' }, function(trans, state) { console.log("Leaving " + state.name); });

onRetain: TransitionStateHookFn

A TransitionStateHookFn called with the state is being retained/kept. See: IHookRegistry.onRetain

A TransitionStateHookFn called with the state is being retained/kept. See: IHookRegistry.onRetain

example

.state({
  name: 'mystate',
  onRetain: function(trans, state) {
    console.log(state.name + " is still active!");
  }
});

Note: The above onRetain on the state declaration is effectively sugar for: ``` transitionService.onRetain({ retained: 'mystate' }, function(trans, state) { console.log(state.name + " is still active!"); });

params: object

Params configuration

Params configuration

An object which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a ParamDeclaration keyed to the name of the parameter.

example

params: {
  param1: {
   type: "int",
   array: true,
   value: []
  },
  param2: {
    value: "index"
  }
}

Type declaration

  • [key: string]: any
parent: string | StateDeclaration

The parent state

The parent state

Normally, a state's parent is implied from the state's name, e.g., "parentstate.childstate".

Alternatively, you can explicitly set the parent state using this property. This allows shorter state names, e.g., <a ui-sref="childstate">Child</a> instead of `Child

When using this property, the state's name should not have any dots in it.

example

var parentstate = {
  name: 'parentstate'
}
var childstate = {
  name: 'childstate',
  parent: 'parentstate'
  // or use a JS var which is the parent StateDeclaration, i.e.:
  // parent: parentstate
}
redirectTo: string | function | object

Synchronously or asynchronously redirects Transitions to a different state/params

Synchronously or asynchronously redirects Transitions to a different state/params

If this property is defined, a Transition directly to this state will be redirected based on the property's value.

  • If the value is a string, the Transition is redirected to the state named by the string.

  • If the property is an object with a state and/or params property, the Transition is redirected to the named state and/or params.

  • If the value is a TargetState the Transition is redirected to the TargetState

  • If the property is a function:

    • The function is called with two parameters:
      • The current Transition
      • An injector which can be used to get dependencies using [[UIRInjector.get]]
    • The return value is processed using the previously mentioned rules.
    • If the return value is a promise, the promise is waited for, then the resolved async value is processed using the same rules.
example

// a string
.state('A', {
  redirectTo: 'A.B'
})

// a {state, params} object
.state('C', {
  redirectTo: { state: 'C.D', params: { foo: 'index' } }
})

// a fn
.state('E', {
  redirectTo: () => "A"
})

// a fn conditionally returning a {state, params}
.state('F', {
  redirectTo: (trans) => {
    if (trans.params().foo < 10)
      return { state: 'F', params: { foo: 10 } };
  }
})

// a fn returning a promise for a redirect
.state('G', {
  redirectTo: (trans) => {
    let svc = trans.injector().get('SomeAsyncService')
    let promise = svc.getAsyncRedirectTo(trans.params.foo);
    return promise;
  }
})
reloadOnSearch: boolean
deprecated

define individual parameters as ParamDeclaration.dynamic

resolve: Array<Resolvable | ResolvableLiteral | ProviderLike> | object

Resolve - a mechanism to asynchronously fetch data, participating in the Transition lifecycle

Resolve - a mechanism to asynchronously fetch data, participating in the Transition lifecycle

The resolve: property defines data (or other dependencies) to be fetched asynchronously when the state is being entered. After the data is fetched, it can be used in views, transition hooks or other resolves that belong to this state, or to any views or resolves that belong to nested states.

As an array

Each array element should either be:

  • a ResolvableLiteral object (a plain old javascript object), e.g., { token: 'token', resolveFn: (http) => http.get('/'), deps: [ Http ] }
  • a Resolvable object, e.g., new Resolvable('token', (http) => http.get('/'), [ Http ])
  • an Angular 2 style provider literal, e.g., { provide: 'token', useFactory: (http) => http.get('/'), deps: [ Http ] }
example

import {Resolvable} from "ui-router-ng2"; // or "angular-ui-router"
...

// ng2 example
resolve: [
  // If you inject `myStateDependency` into a component, you'll get "abc"
  { provide: 'myStateDependency', useFactory: () => 'abc' }, // ng2 style provide literal
  new Resolvable('myFoos', (http, trans) => http.get(`/foos/${trans.params().fooId}`), [Http, Transition])
]

As an object

  • The key (string) is the name of the dependency.
  • The value (function) is an injectable function which returns the dependency, or a promise for the dependency.

Note: You cannot specify a policy for each Resolvable, nor can you use non-string tokens when using the object style resolve: block.

example

// ng1 example
resolve: {
  // If you inject `myStateDependency` into a controller, you'll get "abc"
  myStateDependency: function() {
    return "abc";
  },
  myAsyncData: ['$http', '$transition$' function($http, $transition$) {
    // Return a promise (async) for the data
    return $http.get("/foos/" + $transition$.params().foo);
  }]
}

Lifecycle

Since a resolve function can return a promise, the router will delay entering the state until the promises are ready. If any of the promises are rejected, the Transition is aborted with an Error.

By default, resolves for a state are fetched just before that state is entered. Note that only states which are being entered have their resolves fetched. States that are "retained" do not have their resolves re-fetched. If you are currently in a parent state A and are transitioning to a child state A.B, the previously resolved data for state A can be injected into A.B without delay.

Any resolved data for A.B is retained until A.B is exited, e.g., by transitioning back to the parent state A.

Because of this, resolves are a great place to fetch your application's primary data.

Injecting resolves into other things

During a transition, Resolve data can be injected into:

  • ui-view Controllers
  • TemplateProviders and ControllerProviders
  • Other resolves

Injecting other things into resolves

Since resolve functions are injected, a common pattern is to inject a custom service such as UserService and delegate to a custom service method, such as UserService.list();

Angular 1

An Angular 1 resolve function can inject some special values:

  • $transition$: The current Transition object; information and API about the current transition, such as "to" and "from" State Parameters and transition options.
  • Other resolves: This resolve can depend on another resolve, either from the same state, or from any parent state.
  • $stateParams: (deprecated) The parameters for the current state (Note: these parameter values are

Angular 2

An Angular 2 resolve function can inject some special values:

  • Transition: The current Transition object; information and API about the current transition, such as "to" and "from" State Parameters and transition options.
  • Other resolves: This resolve can depend on another resolve, either from the same state, or from any parent state.
example

// Injecting a resolve into another resolve
resolve: [
  // Define a resolve 'allusers' which delegates to the UserService.list()
  // which returns a promise (async) for all the users
  { provide: 'allusers', useFactory: (UserService) => UserService.list(), deps: [UserService] },

  // Define a resolve 'user' which depends on the allusers resolve.
  // This resolve function is not called until 'allusers' is ready.
  { provide: 'user', (allusers, trans) => _.find(allusers, trans.params().userId, deps: ['allusers', Transition] }
}
resolvePolicy: ResolvePolicy

Sets the resolve policy defaults for all resolves on this state

Sets the resolve policy defaults for all resolves on this state

This should be an ResolvePolicy object.

It can contain the following optional keys/values:

  • when: (optional) defines when the resolve is fetched. Accepted values: "LAZY" or "EAGER"
  • async: (optional) if the transition waits for the resolve. Accepted values: "WAIT", "NOWAIT", "RXWAIT"

See ResolvePolicy for more details.

url: string

The url fragment for the state

The url fragment for the state

A URL fragment (with optional parameters) which is used to match the browser location with this state.

This fragment will be appended to the parent state's URL in order to build up the overall URL for this state. See UrlMatcher for details on acceptable patterns.

examples

url: "/home"
// Define a parameter named 'userid'
url: "/users/:userid"
// param 'bookid' has a custom regexp
url: "/books/{bookid:[a-zA-Z_-]}"
// param 'categoryid' is of type 'int'
url: "/books/{categoryid:int}"
// two parameters for this state
url: "/books/{publishername:string}/{categoryid:int}"
// Query parameters
url: "/messages?before&after"
// Query parameters of type 'date'
url: "/messages?{before:date}&{after:date}"
// Path and query parameters
url: "/messages/:mailboxid?{before:date}&{after:date}"
views: object

An optional object used to define multiple named views.

An optional object used to define multiple named views.

Each key is the name of a view, and each value is a Ng2ViewDeclaration. Unnamed views are internally renamed to $default.

A view's name is used to match an active <ui-view> directive in the DOM. When the state is entered, the state's views are activated and then matched with active <ui-view> directives:

  • The view's name is processed into a ui-view target:

    • ui-view address: an address to a ui-view
    • state anchor: the state to anchor the address to

    Examples:

    Targets three named ui-views in the parent state's template

example

views: {
  header: HeaderComponent,
  body: BodyComponent,
  footer: FooterComponent
}
example

// Targets named ui-view="header" in the template of the ancestor state 'top'
// and the named `ui-view="body" from the parent state's template.
views: {
  'header@top': MsgHeaderComponent,
  'body': MessagesComponent
}

View targeting details

There are a few styles of view addressing/targeting. The most common is a simple ui-view name

Simple ui-view name

Addresses without an @ are anchored to the parent state.

example

// target the `<div ui-view='foo'></div>` created in the parent state's view
views: { foo: {...} }

View name anchored to a state

You can anchor the ui-view name to a specific state by including an @

example

// target the `<div ui-view='foo'></div>` which was created in a
// view owned by the state `bar.baz`
views: { 'foo@bar.baz': {...} }

Absolute addressing

You can address a ui-view absolutely, using dotted notation, by prefixing the address with a !. Dotted addresses map to the hierarchy of ui-views active in the DOM:

example

// absolutely target the `<div ui-view='nested'></div>`... which was created
// in the unnamed/$default root `<ui-view></ui-view>`
views: { '!$default.nested': {...} }

Relative addressing

Absolute addressing is actually relative addressing, only anchored to the unnamed root state. You can also use relative addressing anchored to any state, in order to target a target deeply nested ui-views:

example


// target the `<div ui-view='bar'></div>`... which was created inside the
// `<div ui-view='bar'></div>`... which was created inside the parent state's template.
views: { 'foo.bar': {...} }
example

```js

// target the <div ui-view='bar'></div>... which was created in // <div ui-view='foo'></div>... which was created in a template crom the state baz.qux views: { 'foo.bar@baz.qux': {...} }


State component: and views: incompatiblity

If a state has a views object, the state-level component: property is ignored. Therefore, if any view for a state is declared in the views object, then all of the state's views must be defined in the views object.

Type declaration

Generated using TypeDoc