Class Component

public

A Component is a view that is completely isolated. Properties accessed in its templates go to the view object and actions are targeted at the view object. There is no access to the surrounding context or outer controller; all contextual information must be passed in.

The easiest way to create a Component is via a template. If you name a template app/components/my-foo.hbs, you will be able to use {{my-foo}} in other templates, which will make an instance of the isolated component.

foo.hbs
1
{{person-profile person=currentUser}}
profile.hbs
1
2
3
<h1>{{person.title}}</h1>
<img src={{person.avatar}}>
<p class='signature'>{{person.signature}}</p>

You can use yield inside a template to include the contents of any block attached to the component. The block will be executed in the context of the surrounding context or outer controller:

1
2
3
4
{{#person-profile person=currentUser}}
  <p>Admin mode</p>
  {{! Executed in the controller's context. }}
{{/person-profile}}
profile.hbs
1
2
3
<h1>{{person.title}}</h1>
{{! Executed in the component's context. }}
{{yield}} {{! block contents }}

If you want to customize the component, in order to handle events or actions, you implement a subclass of Component named after the name of the component.

For example, you could implement the action hello for the person-profile component:

profile.js
1
2
3
4
5
6
7
8
9
import Component from '@ember/component';

export default Component.extend({
  actions: {
    hello(name) {
      console.log("Hello", name);
    }
  }
});

And then use it in the component's template:

profile.hbs
1
2
3
4
5
<h1>{{person.title}}</h1>
{{yield}} <!-- block contents -->
<button {{action 'hello' person.name}}>
  Say Hello to {{person.name}}
</button>

Components must have a - in their name to avoid conflicts with built-in controls that wrap HTML elements. This is consistent with the same requirement in web components.

HTML Tag

The default HTML tag name used for a component's DOM representation is div. This can be customized by setting the tagName property. The following component class:

paragraph.js
1
2
3
4
5
import Component from '@ember/component';

export default Component.extend({
  tagName: 'em'
});

Would result in instances with the following HTML:

1
<em id="ember1" class="ember-view"></em>

HTML class Attribute

The HTML class attribute of a component's tag can be set by providing a classNames property that is set to an array of strings:

widget.js
1
2
3
4
5
import Component from '@ember/component';

export default Component.extend({
  classNames: ['my-class', 'my-other-class']
});

Will result in component instances with an HTML representation of:

1
<div id="ember1" class="ember-view my-class my-other-class"></div>

class attribute values can also be set by providing a classNameBindings property set to an array of properties names for the component. The return value of these properties will be added as part of the value for the components's class attribute. These properties can be computed properties:

widget.js
1
2
3
4
5
6
7
8
9
10
11
import Component from '@ember/component';
import { computed } from '@ember/object';

export default Component.extend({
  classNameBindings: ['propertyA', 'propertyB'],

  propertyA: 'from-a',
  propertyB: computed(function() {
    if (someLogic) { return 'from-b'; }
  })
});

Will result in component instances with an HTML representation of:

1
<div id="ember1" class="ember-view from-a from-b"></div>

If the value of a class name binding returns a boolean the property name itself will be used as the class name if the property is true. The class name will not be added if the value is false or undefined.

widget.js
1
2
3
4
5
6
7
import Component from '@ember/component';

export default Component.extend({
  classNameBindings: ['hovered'],

  hovered: true
});

Will result in component instances with an HTML representation of:

1
<div id="ember1" class="ember-view hovered"></div>

When using boolean class name bindings you can supply a string value other than the property name for use as the class HTML attribute by appending the preferred value after a ":" character when defining the binding:

widget.js
1
2
3
4
5
6
7
import Component from '@ember/component';

export default Component.extend({
  classNameBindings: ['awesome:so-very-cool'],

  awesome: true
});

Will result in component instances with an HTML representation of:

1
<div id="ember1" class="ember-view so-very-cool"></div>

Boolean value class name bindings whose property names are in a camelCase-style format will be converted to a dasherized format:

widget.js
1
2
3
4
5
6
7
import Component from '@ember/component';

export default Component.extend({
  classNameBindings: ['isUrgent'],

  isUrgent: true
});

Will result in component instances with an HTML representation of:

1
<div id="ember1" class="ember-view is-urgent"></div>

Class name bindings can also refer to object values that are found by traversing a path relative to the component itself:

widget.js
1
2
3
4
5
6
7
8
9
10
import Component from '@ember/component';
import EmberObject from '@ember/object';

export default Component.extend({
  classNameBindings: ['messages.empty'],

  messages: EmberObject.create({
    empty: true
  })
});

Will result in component instances with an HTML representation of:

1
<div id="ember1" class="ember-view empty"></div>

If you want to add a class name for a property which evaluates to true and and a different class name if it evaluates to false, you can pass a binding like this:

widget.js
1
2
3
4
5
6
import Component from '@ember/component';

export default Component.extend({
  classNameBindings: ['isEnabled:enabled:disabled'],
  isEnabled: true
});

Will result in component instances with an HTML representation of:

1
<div id="ember1" class="ember-view enabled"></div>

When isEnabled is false, the resulting HTML representation looks like this:

1
<div id="ember1" class="ember-view disabled"></div>

This syntax offers the convenience to add a class if a property is false:

widget.js
1
2
3
4
5
6
7
import Component from '@ember/component';

// Applies no class when isEnabled is true and class 'disabled' when isEnabled is false
export default Component.extend({
  classNameBindings: ['isEnabled::disabled'],
  isEnabled: true
});

Will result in component instances with an HTML representation of:

1
<div id="ember1" class="ember-view"></div>

When the isEnabled property on the component is set to false, it will result in component instances with an HTML representation of:

1
<div id="ember1" class="ember-view disabled"></div>

Updates to the value of a class name binding will result in automatic update of the HTML class attribute in the component's rendered HTML representation. If the value becomes false or undefined the class name will be removed. Both classNames and classNameBindings are concatenated properties. See EmberObject documentation for more information about concatenated properties.

HTML Attributes

The HTML attribute section of a component's tag can be set by providing an attributeBindings property set to an array of property names on the component. The return value of these properties will be used as the value of the component's HTML associated attribute:

anchor.js
1
2
3
4
5
6
7
8
import Component from '@ember/component';

export default Component.extend({
  tagName: 'a',
  attributeBindings: ['href'],

  href: 'http://google.com'
});

Will result in component instances with an HTML representation of:

1
<a id="ember1" class="ember-view" href="http://google.com"></a>

One property can be mapped on to another by placing a ":" between the source property and the destination property:

anchor.js
1
2
3
4
5
6
7
8
import Component from '@ember/component';

export default Component.extend({
  tagName: 'a',
  attributeBindings: ['url:href'],

  url: 'http://google.com'
});

Will result in component instances with an HTML representation of:

1
<a id="ember1" class="ember-view" href="http://google.com"></a>

Namespaced attributes (e.g. xlink:href) are supported, but have to be mapped, since : is not a valid character for properties in Javascript:

use.js
1
2
3
4
5
6
7
8
import Component from '@ember/component';

export default Component.extend({
  tagName: 'use',
  attributeBindings: ['xlinkHref:xlink:href'],

  xlinkHref: '#triangle'
});

Will result in component instances with an HTML representation of:

1
<use xlink:href="#triangle"></use>

If the return value of an attributeBindings monitored property is a boolean the attribute will be present or absent depending on the value:

input.js
1
2
3
4
5
6
7
8
import Component from '@ember/component';

export default Component.extend({
  tagName: 'input',
  attributeBindings: ['disabled'],

  disabled: false
});

Will result in a component instance with an HTML representation of:

1
<input id="ember1" class="ember-view" />

attributeBindings can refer to computed properties:

input.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import Component from '@ember/component';
import { computed } from '@ember/object';

export default Component.extend({
  tagName: 'input',
  attributeBindings: ['disabled'],

  disabled: computed(function() {
    if (someLogic) {
      return true;
    } else {
      return false;
    }
  })
});

To prevent setting an attribute altogether, use null or undefined as the return value of the attributeBindings monitored property:

input.js
1
2
3
4
5
6
7
import Component from '@ember/component';

export default Component.extend({
  tagName: 'form',
  attributeBindings: ['novalidate'],
  novalidate: null
});

Updates to the property of an attribute binding will result in automatic update of the HTML attribute in the component's rendered HTML representation. attributeBindings is a concatenated property. See EmberObject documentation for more information about concatenated properties.

Layouts

See Ember.Templates.helpers.yield for more information.

Layout can be used to wrap content in a component. In addition to wrapping content in a Component's template, you can also use the public layout API in your Component JavaScript.

profile.hbs
1
2
  <h1>Person's Title</h1>
  <div class='details'>{{yield}}</div>
profile.js
1
2
3
4
5
6
  import Component from '@ember/component';
  import layout from '../templates/components/person-profile';

  export default Component.extend({
    layout
  });

The above will result in the following HTML output:

1
2
3
4
5
  <h1>Person's Title</h1>
  <div class="details">
    <h2>Chief Basket Weaver</h2>
    <h3>Fisherman Industries</h3>
  </div>

Responding to Browser Events

Components can respond to user-initiated events in one of three ways: method implementation, through an event manager, and through {{action}} helper use in their template or layout.

Method Implementation

Components can respond to user-initiated events by implementing a method that matches the event name. A jQuery.Event object will be passed as the argument to this method.

widget.js
1
2
3
4
5
6
7
8
import Component from '@ember/component';

export default Component.extend({
  click(event) {
    // will be called when an instance's
    // rendered element is clicked
  }
});

{{action}} Helper

See Ember.Templates.helpers.action.

Event Names

All of the event handling approaches described above respond to the same set of events. The names of the built-in events are listed below. (The hash of built-in events exists in Ember.EventDispatcher.) Additional, custom events can be registered by using Application.customEvents.

Touch events:

  • touchStart
  • touchMove
  • touchEnd
  • touchCancel

Keyboard events:

  • keyDown
  • keyUp
  • keyPress

Mouse events:

  • mouseDown
  • mouseUp
  • contextMenu
  • click
  • doubleClick
  • mouseMove
  • focusIn
  • focusOut
  • mouseEnter
  • mouseLeave

Form events:

  • submit
  • change
  • focusIn
  • focusOut
  • input

HTML5 drag and drop events:

  • dragStart
  • drag
  • dragEnter
  • dragLeave
  • dragOver
  • dragEnd
  • drop

Show:

The collection of functions, keyed by name, available on this ActionHandler as action targets.

These functions will be invoked when a matching {{action}} is triggered from within a template and the application's current route is this route.

Actions can also be invoked from other parts of your application via ActionHandler#send.

The actions hash will inherit action handlers from the actions hash defined on extended parent classes or mixins rather than just replace the entire hash, e.g.:

banner.js
1
2
3
4
5
6
7
8
9
import Mixin from '@ember/mixin';

export default Mixin.create({
  actions: {
    displayBanner(msg) {
      // ...
    }
  }
});
app/routes/welcome.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import Route from '@ember/routing/route';
import CanDisplayBanner from '../mixins/can-display-banner';

export default Route.extend(CanDisplayBanner, {
  actions: {
    playMusic() {
      // ...
    }
  }
});

// `WelcomeRoute`, when active, will be able to respond
// to both actions, since the actions hash is merged rather
// then replaced when extending mixins / parent classes.
this.send('displayBanner');
this.send('playMusic');

Within a Controller, Route or Component's action handler, the value of the this context is the Controller, Route or Component object:

app/routes/song.js
1
2
3
4
5
6
7
8
9
10
11
import Route from '@ember/routing/route';

export default Route.extend({
  actions: {
    myAction() {
      this.controllerFor("song");
      this.transitionTo("other.route");
      ...
    }
  }
});

It is also possible to call this._super(...arguments) from within an action handler if it overrides a handler defined on a parent class or mixin:

Take for example the following routes:

route.js
1
2
3
4
5
6
7
8
9
import Mixin from '@ember/mixin';

export default Mixin.create({
  actions: {
    debugRouteInformation() {
      console.debug("It's a-me, console.debug!");
    }
  }
});
debug.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import Route from '@ember/routing/route';
import DebugRoute from '../mixins/debug-route';

export default Route.extend(DebugRoute, {
  actions: {
    debugRouteInformation() {
      // also call the debugRouteInformation of mixed in DebugRoute
      this._super(...arguments);

      // show additional annoyance
      window.alert(...);
    }
  }
});

Bubbling

By default, an action will stop bubbling once a handler defined on the actions hash handles it. To continue bubbling the action, you must return true from the handler:

app/router.js
1
2
3
4
5
Router.map(function() {
  this.route("album", function() {
    this.route("song");
  });
});
app/routes/album.js
1
2
3
4
5
6
7
8
import Route from '@ember/routing/route';

export default Route.extend({
  actions: {
    startPlaying: function() {
    }
  }
});
song.js
1
2
3
4
5
6
7
8
9
10
11
12
13
import Route from '@ember/routing/route';

export default Route.extend({
  actions: {
    startPlaying() {
      // ...

      if (actionShouldAlsoBeTriggeredOnParentRoute) {
        return true;
      }
    }
  }
});

The WAI-ARIA role of the control represented by this view. For example, a button may have a role of type 'button', or a pane may have a role of type 'alertdialog'. This property is used by assistive software to help visually challenged users navigate rich web applications.

The full list of valid WAI-ARIA roles is available at: http://www.w3.org/TR/wai-aria/roles#roles_categorization

A list of properties of the view to apply as attributes. If the property is a string value, the value of that string will be applied as the value for an attribute of the property's name.

The following example creates a tag like <div priority="high" />.

component.js
1
2
3
4
5
6
import Component from '@ember/component';

export default Component.extend({
  attributeBindings: ['priority'],
  priority: 'high'
});

If the value of the property is a Boolean, the attribute is treated as an HTML Boolean attribute. It will be present if the property is true and omitted if the property is false.

The following example creates markup like <div visible />.

component.js
1
2
3
4
5
6
import Component from '@ember/component';

export default Component.extend({
  attributeBindings: ['visible'],
  visible: true
});

If you would prefer to use a custom value instead of the property name, you can create the same markup as the last example with a binding like this:

component.js
1
2
3
4
5
6
import Component from '@ember/component';

export default Component.extend({
  attributeBindings: ['isVisible:visible'],
  isVisible: true
});

This list of attributes is inherited from the component's superclasses, as well.

A list of properties of the view to apply as class names. If the property is a string value, the value of that string will be applied as a class name.

1
2
3
4
5
6
// Applies the 'high' class to the view element
import Component from '@ember/component';
Component.extend({
  classNameBindings: ['priority'],
  priority: 'high'
});

If the value of the property is a Boolean, the name of that property is added as a dasherized class name.

1
2
3
4
5
6
// Applies the 'is-urgent' class to the view element
import Component from '@ember/component';
Component.extend({
  classNameBindings: ['isUrgent'],
  isUrgent: true
});

If you would prefer to use a custom value instead of the dasherized property name, you can pass a binding like this:

1
2
3
4
5
6
// Applies the 'urgent' class to the view element
import Component from '@ember/component';
Component.extend({
  classNameBindings: ['isUrgent:urgent'],
  isUrgent: true
});

This list of properties is inherited from the component's superclasses as well.

Standard CSS class names to apply to the view's outer element. This property automatically inherits any class names defined by the view's superclasses as well.

Defines the properties that will be concatenated from the superclass (instead of overridden).

By default, when you extend an Ember class a property defined in the subclass overrides a property with the same name that is defined in the superclass. However, there are some cases where it is preferable to build up a property's value by combining the superclass' property value with the subclass' value. An example of this in use within Ember is the classNames property of Ember.View.

Here is some sample code showing the difference between a concatenated property and a normal one:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import EmberObject from '@ember/object';

const Bar = EmberObject.extend({
  // Configure which properties to concatenate
  concatenatedProperties: ['concatenatedProperty'],

  someNonConcatenatedProperty: ['bar'],
  concatenatedProperty: ['bar']
});

const FooBar = Bar.extend({
  someNonConcatenatedProperty: ['foo'],
  concatenatedProperty: ['foo']
});

let fooBar = FooBar.create();
fooBar.get('someNonConcatenatedProperty'); // ['foo']
fooBar.get('concatenatedProperty'); // ['bar', 'foo']

This behavior extends to object creation as well. Continuing the above example:

1
2
3
4
5
6
let fooBar = FooBar.create({
  someNonConcatenatedProperty: ['baz'],
  concatenatedProperty: ['baz']
})
fooBar.get('someNonConcatenatedProperty'); // ['baz']
fooBar.get('concatenatedProperty'); // ['bar', 'foo', 'baz']

Adding a single property that is not an array will just add it in the array:

1
2
3
4
let fooBar = FooBar.create({
  concatenatedProperty: 'baz'
})
view.get('concatenatedProperty'); // ['bar', 'foo', 'baz']

Using the concatenatedProperties property, we can tell Ember to mix the content of the properties.

In Component the classNames, classNameBindings and attributeBindings properties are concatenated.

This feature is available for you to use throughout the Ember object model, although typical app developers are likely to use it infrequently. Since it changes expectations about behavior of properties, you should properly document its usage in each individual concatenated property (to not mislead your users to think they can override the property in a subclass).

Returns the current DOM element for the view.

The HTML id of the component's element in the DOM. You can provide this value yourself but it must be unique (just as in HTML):

1
{{my-component elementId="a-really-cool-id"}}

If not manually set a default value will be provided by the framework. Once rendered an element's elementId is considered immutable and you should never change it. If you need to compute a dynamic value for the elementId, you should do this when the component or element is being instantiated:

1
2
3
4
5
6
7
8
export default Component.extend({
  init() {
    this._super(...arguments);

    var index = this.get('index');
    this.set('elementId', `component-id${index}`);
  }
});

Destroyed object property flag.

if this property is true the observers and bindings were already removed by the effect of calling the destroy() method.

Destruction scheduled flag. The destroy() method has been called.

The object stays intact until the end of the run loop at which point the isDestroyed flag is set.

If false, the view will appear hidden in DOM.

Layout can be used to wrap content in a component.

Defines the properties that will be merged from the superclass (instead of overridden).

By default, when you extend an Ember class a property defined in the subclass overrides a property with the same name that is defined in the superclass. However, there are some cases where it is preferable to build up a property's value by merging the superclass property value with the subclass property's value. An example of this in use within Ember is the queryParams property of routes.

Here is some sample code showing the difference between a merged property and a normal one:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import EmberObject from '@ember/object';

const Bar = EmberObject.extend({
  // Configure which properties are to be merged
  mergedProperties: ['mergedProperty'],

  someNonMergedProperty: {
    nonMerged: 'superclass value of nonMerged'
  },
  mergedProperty: {
    page: { replace: false },
    limit: { replace: true }
  }
});

const FooBar = Bar.extend({
  someNonMergedProperty: {
    completelyNonMerged: 'subclass value of nonMerged'
  },
  mergedProperty: {
    limit: { replace: false }
  }
});

let fooBar = FooBar.create();

fooBar.get('someNonMergedProperty');
// => { completelyNonMerged: 'subclass value of nonMerged' }
//
// Note the entire object, including the nonMerged property of
// the superclass object, has been replaced

fooBar.get('mergedProperty');
// => {
//   page: {replace: false},
//   limit: {replace: false}
// }
//
// Note the page remains from the superclass, and the
// `limit` property's value of `false` has been merged from
// the subclass.

This behavior is not available during object create calls. It is only available at extend time.

In Route the queryParams property is merged.

This feature is available for you to use throughout the Ember object model, although typical app developers are likely to use it infrequently. Since it changes expectations about behavior of properties, you should properly document its usage in each individual merged property (to not mislead your users to think they can override the property in a subclass).

Available since v1.13.0

Enables components to take a list of parameters as arguments. For example, a component that takes two parameters with the names name and age:

component.js
1
2
3
4
5
6
7
8
9
import Component from '@ember/component';

let MyComponent = Component.extend();

MyComponent.reopenClass({
  positionalParams: ['name', 'age']
});

export default MyComponent;

It can then be invoked like this:

1
{{my-component "John" 38}}

The parameters can be referred to just like named parameters:

1
Name: {{name}}, Age: {{age}}.

Using a string instead of an array allows for an arbitrary number of parameters:

component.js
1
2
3
4
5
6
7
8
9
import Component from '@ember/component';

let MyComponent = Component.extend();

MyComponent.reopenClass({
  positionalParams: 'names'
});

export default MyComponent;

It can then be invoked like this:

1
{{my-component "John" "Michael" "Scott"}}

The parameters can then be referred to by enumerating over the list:

1
{{#each names as |name|}}{{name}}{{/each}}

Tag name for the view's outer element. The tag name is only used when an element is first created. If you change the tagName for an element, you must destroy and recreate the view element.

By default, the render buffer will use a <div> tag for views.