Class Component

public

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>

File System Nesting

Components can be nested inside sub-folders for logical groupping. For example, if we placed our template in app/templates/components/person/short-profile.hbs, we can invoke it as <Person::ShortProfile />:

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

Or equivalently, {{person/short-profile}}:

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

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.name}}</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.

One example is to add computed properties to your component:

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

export default Component.extend({
  displayName: computed('person.title', 'person.firstName', 'person.lastName', function() {
    let { title, firstName, lastName } = this;

    if (title) {
      return `${title} ${lastName}`;
    } else {
      return `${firstName} ${lastName};
    }
  })
});

And then use it in the component's template:

profile.hbs
1
2
<h1>{{this.displayName}}</h1>
{{yield}}

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
12
import Component from '@ember/component';
import { computed } from '@ember/object';

export default Component.extend({
  classNames: ['my-class', 'my-other-class'],
  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 my-class my-other-class from-a from-b"></div>

Note that classNames and classNameBindings is in addition to the class attribute passed with the angle bracket invocation syntax. Therefore, if this component was invoked like so:

1
<MyWidget class="from-invocation" />

The resulting HTML will look similar to this:

1
<div id="ember1" class="from-invocation ember-view my-class my-other-class 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.

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

HTML attributes passed with angle bracket invocations will take precedence over those specified in attributeBindings. Therefore, if this component was invoked like so:

1
<MyAnchor href="http://bing.com" @url="http://google.com" />

The resulting HTML will looks like this:

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

Note that the href attribute is ultimately set to http://bing.com, despite it having attribute binidng to the url property, which was set to http://google.com.

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: passing actions with angle bracket invocation, adding event handler methods to the component's class, or adding actions to the component's template.

Passing Actions With Angle Bracket Invoation

For one-off events specific to particular instance of a component, it is possible to pass actions to the component's element using angle bracket invoation syntax.

1
2
3
<MyWidget {{action 'firstWidgetClicked'}} />

<MyWidget {{action 'secondWidgetClicked'}} />

In this case, when the first component is clicked on, Ember will invoke the firstWidgetClicked action. When the second component is clicked on, Ember will invoke the secondWidgetClicked action instead.

Besides {{action}}, it is also possible to pass any arbitrary element modifiers using the angle bracket invocation syntax.

Event Handler Methods

Components can also respond to user-initiated events by implementing a method that matches the event name. This approach is appropiate when the same event should be handled by all instances of the same component.

An event object will be passed as the argument to the event handler method.

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

export default Component.extend({
  click(event) {
    // `event.target` is either the component's element or one of its children
    let tag = event.target.tagName.toLowerCase();
    console.log('clicked on a `<${tag}>` HTML element!');
  }
});

In this example, whenever the user clicked anywhere inside the component, it will log a message to the console.

It is possible to handle event types other than click by implementing the following event handler methods. In addition, 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

Drag and drop events:

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

{{action}} Helper

Instead of handling all events of a particular type anywhere inside the component's element, you may instead want to limit it to a particular element in the component's template. In this case, it would be more convenient to implement an action instead.

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.name}}</h1>

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

See Ember.Templates.helpers.action.