MaYaN
MaYaN

Reputation: 7006

How can I use select2 as an Aurelia attribute?

This is not a duplicate of: aurelia-trying-to-load-html-from-select2

I am trying to add a select2 dropdown to the Aurelia Contact Manager but I am having problems getting it to work.

My aurelia.json looks:

...
{
  "name": "select2",
  "path": "../node_modules/select2/dist",
  "main": "js/select2",
  "deps": ["jquery"],
  "resources": [
    "css/select2.css"
  ]
}
...

And the custom attribute:

import {autoinject, customAttribute} from 'aurelia-framework';

import * as $ from 'jquery';
import 'select2';
import 'select2/css/select2.css!';

@customAttribute('select2')
@autoinject
export class SelectCustomAttribute {
    element: Element;

    constructor(element: Element) {
        this.element = element;
    }

    attached(): void {
        $(this.element)
            .select2({
                placeholder: 'Select!'
            })
            .on('change', e => {
                if(e.originalEvent) { return; }
            });
    }

    detached(): void {
        $(this.element).select2('destroy').off('change');
    }
}

Building the application fails with:

[Error: ENOENT: no such file or directory, open 'C:\Users\MyApp\node_modules\select2\dist\css\select2.css.js']

Removing the import 'select2/css/select2.css!'; makes it compile but then I would have to load the css manually wherever I want to use this attribute which defeats the purpose of having the attribute at the first place:

<require from="select2/css/select2.css"></require>
<section class="row container">
    <select select2>
    <option>Mustard</option>
    <option>Ketchup</option>
    <option>Relish</option>
    </select>
</section>

Upvotes: 1

Views: 572

Answers (1)

peinearydevelopment
peinearydevelopment

Reputation: 11464

Based on the error you are reporting, there are a few things you will need to do. The index.d.ts file for angular-protractor is causing a naming conflict with jQuery's .d.ts file.

In typings/globals/angular-protractor/index.d.ts comment out like 1839(declare var $: cssSelectorHelper).

Add the following to your aurelia.json file.

{
  "name": "select2",
  "path": "../node_modules/select2/dist",
  "main": "js/select2.min",
  "resources": [ 
    "css/select2.min.css"
  ]
}

There is an issue filed on the aurelia-cli around importing css files. There are a few solutions there as to how to include .css files. The approach I took was to add <require from="select2/css/select2.min.css"></require> to my app.ts file.

Upvotes: 1

Related Questions