Class Component

public
import Component from '@ember/component';

A component is an isolated piece of UI, represented by a template and an optional class. When a component has a class, its template's this value is an instance of the component class.

Template-only Components

The simplest way to create a component is to create a template file in app/templates/components. For example, if you name a template app/templates/components/person-profile.hbs:

profile.hbs
1
2
3
<h1>{{@person.name}}</h1>
<img src={{@person.avatar}}>
<p class='signature'>{{@person.signature}}</p>

You will be able to use <PersonProfile /> to invoke this component elsewhere in your application:

app/templates/application.hbs
1
<PersonProfile @person={{this.currentUser}} />

Note that component names are capitalized here in order to distinguish them from regular HTML elements, but they are dasherized in the file system.

While the angle bracket invocation form is generally preferred, it is also possible to invoke the same component with the {{person-profile}} syntax:

app/templates/application.hbs
1
{{person-profile person=this.currentUser}}

Note that with this syntax, you use dashes in the component name and arguments are passed without the @ sign.

In both cases, Ember will render the content of the component template we created above. The end result will be something like this:

1
2
3
<h1>Tomster</h1>
<img src="https://emberjs.com/tomster.jpg">
<p class='signature'>Out of office this week</p>

Yielding Contents

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

1
2
3
4
<PersonProfile @person={{this.currentUser}}>
  <p>Admin mode</p>
  {{! Executed in the current context. }}
</PersonProfile>

or

1
2
3
4
{{#person-profile person=this.currentUser}}
  <p>Admin mode</p>
  {{! Executed in the current context. }}
{{/person-profile}}
profile.hbs
1
2
<h1>{{person.title}}</h1>
{{yield}}

Customizing Components With JavaScript

If you want to customize the component in order to handle events, transform arguments or maintain internal state, you implement a subclass of 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>

When the user clicks the button, Ember will invoke the hello action, passing in the current value of person.name as an argument.

For historical reasons, components must have a - in their name when invoked using the {{ syntax.

Customizing a Component's HTML Element in JavaScript

HTML Tag

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

Consider the following component class:

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

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

When invoked, this component would produce output that looks something like this:

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']
});

Invoking this component will produce output that looks like this:

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'; }
  })
});

Invoking this component will produce HTML that looks like:

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
});

Invoking this component will produce HTML that looks like:

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

Custom Class Names for Boolean Values

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
});

Invoking this component will produce HTML that looks like:

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
});

Invoking this component will produce HTML that looks like:

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
  })
});

Invoking this component will produce HTML that looks like:

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
});

Invoking this component will produce HTML that looks like:

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
});

Invoking this component when the isEnabled property is true will produce HTML that looks like:

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

Invoking it when the isEnabled property on the component is false will produce HTML that looks like:

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'
});

Invoking this component will produce HTML that looks like:

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'
});

Invoking this component will produce HTML that looks like:

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'
});

Invoking this component will produce HTML that looks like:

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

If the value of a property monitored by attributeBindings 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
});

Invoking this component will produce HTML that looks like:

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 value of the property used in attributeBindings:

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 HTML output.

attributeBindings is a concatenated property. See EmberObject documentation for more information about concatenated properties.

Layouts

The layout property can be used to dynamically specify a template associated with a component class, instead of relying on Ember to link together a component class and a template based on file names.

In general, applications should not use this feature, but it's commonly used in addons for historical reasons.

The layout property should be set to the default export of a template module, which is the name of a template file without the .hbs extension.

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
  });

If you invoke the component:

1
2
3
4
<PersonProfile>
  <h2>Chief Basket Weaver</h2>
  <h3>Fisherman Industries</h3>
</PersonProfile>

or

1
2
3
4
{{#person-profile}}
  <h2>Chief Basket Weaver</h2>
  <h3>Fisherman Industries</h3>
{{/person-profile}}

It 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>

Handling 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. An 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 with a browser event 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