How do you set default value for component argument when you use es2015 class syntax?

It is common to give a default value for a component argument, then allow users to pass a new value to overwrite it, but it doesn’t work as it should be if you use es2015 syntax.

For example

export default class FooBar extends Component {
  name = 'default';
}
{{foo-bar}}  {{!-- name is "default" --}}
{{foo-bar name="nightire"}} {{!-- name is still "default"}}

there is a workaround:

export default class FooBar extends Component.extend({
  name: 'default'
}) {

}
{{foo-bar}}  {{!-- name is "default" --}}
{{foo-bar name="nightire"}} {{!-- name is "nightire" now}}

but I’m wondering why? and is there a better solution exists?

Hello :wave:

I have been using defaultTo from lodash to accomplish this.

import Component from '@ember/component';
import { defaultTo } from 'lodash';

export default class MyComponent extends Component {
  pageSize = defaultTo(this.pageSize, 20);
  currentPage = defaultTo(this.currentPage, 1);
}
1 Like

:dragon_face: THAR BE DRAGONS :dragon:

This is actually the subject of an active RFC over at emberjs/rfcs#337 (thanks @pzuraq) , would love your feedback over there…

3 Likes