Modifiers¶
Components have different life-cycles.
We can use modifiers to make use of these life cycles, either the modifiers Ember provides, like did-insert to do something with a component on the first render or by writing our own, using the CLI via an ember plugin called ember-modifier
that allows the command
$ ember g modifier <name>
to create a modifier called <name>
in the app/modifiers/
directory.
We want to do the latter.
First, run
$ yarn ember install ember-modifier
in your terminal.
The official documentation presents a useful example that creates an autofocus
functionality that might be useful.
To create the modifier, run
$ yarn ember g modifier autofocus
Inside app/modifiers/autofocus.js
you can either use the shorthand arrow function shown in the official example
import { modifier } from "ember-modifier";
export default modifier(element => element.focus());
or write the longer version, keeping the function declaration using the function
keyword:
import { modifier } from 'ember-modifier';
export default modifier(function autofocus(element) {element.focus()});
You can call your modifier on the element you want to focus initially by adding {{autofocus}}
to the element.
Update the first <Input />
component in app/components/login-page
to
and run your app. When you navigate to the login route, the first input field should be focussed.