Class Component

public

A component is a reusable UI element that consists of a .hbs template and an optional JavaScript class that defines its behavior. For example, someone might make a button in the template and handle the click behavior in the JavaScript file that shares the same name as the template.

Components are broken down into two categories:

  • Components without JavaScript, that are based only on a template. These are called Template-only or TO components.
  • Components with JavaScript, which consist of a template and a backing class.

Ember ships with two types of JavaScript classes for components:

  1. Glimmer components, imported from @glimmer/component, which are the default component's for Ember Octane (3.15) and more recent editions.
  2. Classic components, imported from @ember/component, which were the default for older editions of Ember (pre 3.15).

Below is the documentation for Classic components. If you are looking for the API documentation for Template-only or Glimmer components, it is available here.

Defining a Classic Component

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:

app/components/person-profile.js
import Component from '@ember/component';

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

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

And then use it in the component's template:

app/templates/components/person-profile.hbs
<h1>{{this.displayName}}</h1>
{{yield}}

Customizing a Classic 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:

app/components/emphasized-paragraph.js
import Component from '@ember/component';

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

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

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

app/components/my-widget.js
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:

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

app/components/my-widget.js
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:

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

<MyWidget class="from-invocation" />

The resulting HTML will look similar to this:

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

app/components/my-widget.js
import Component from '@ember/component';

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

  hovered: true
});

Invoking this component will produce HTML that looks like:

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

app/components/my-widget.js
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:

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

app/components/my-widget.js
import Component from '@ember/component';

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

  isUrgent: true
});

Invoking this component will produce HTML that looks like:

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

app/components/my-widget.js
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:

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

app/components/my-widget.js
import Component from '@ember/component';

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

Invoking this component will produce HTML that looks like:

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

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

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

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

app/components/my-widget.js
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:

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

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

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

app/components/my-anchor.js
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:

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

app/components/my-anchor.js
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:

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

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

The resulting HTML will looks like this:

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

app/components/my-use.js
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:

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

app/components/my-text-input.js
import Component from '@ember/component';

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

  disabled: false
});

Invoking this component will produce HTML that looks like:

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

attributeBindings can refer to computed properties:

app/components/my-text-input.js
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:

app/components/my-text-input.js
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.

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

  export default Component.extend({
    layout
  });

If you invoke the component:

<PersonProfile>
  <h2>Chief Basket Weaver</h2>
  <h3>Fisherman Industries</h3>
</PersonProfile>

or

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

It will result in the following HTML output:

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

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

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

app/components/my-widget.js
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
  • focusIn
  • focusOut

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:

app/components/person-profile.js
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:

app/templates/components/person-profile.hbs
<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.