Introduction to Components
Learn to render components in templates.
We'll cover the following
Ember components allow us to convert markup text and styles into reusable code. Other than the resusability perspective, components also help us organize our code. Components can also be reused across different applications. Ember components are made up of two files: a Handlebars template file and a JavaScript component file. The Handlebars template is an hbs
file that contains the UI of that component. The JavaScript component file handles all the events on that UI.
Creating a component
There are two ways to create components. We can create components manually by adding the files in app/components
, or we can run the following Ember CLI command:
ember g component <component-name>
Components must have a -
in their name to avoid a clash with HTML element names. The command above creates an hbs
file in app/components
and a test file in tests/integration/components
.
In most cases, we only need to reuse a UI component. However, to handle its events, we need to create the JavaScript file of that component by running the following command:
ember g component-class <component-name>
This creates a JavaScript component file in app/components
.
Let’s create a test component by running the following command. Then, we’ll render it inside our template:
ember g component test-comp
The command above generates a test-comp.hbs
file in app/component
. Let’s open it in the code widget and add some content to it:
Get hands-on with 1400+ tech skills courses.