1

In an angular-cli project, i have to use a simple jquery/bootstrap plugin: boostrap-filestyle.

I would like to use it via data-attribute, without call to jquery directly.

Steps:

npm install --save jquery bootstrap-filestyle

Add to angular-cli.json:

"scripts": [
  "../node_modules/jquery/dist/jquery.min.js",
  "../node_modules/bootstrap/dist/js/bootstrap.min.js",
  "../node_modules/bootstrap-filestyle/src/bootstrap-filestyle.min.js"
],

Bootstrap seems to work. But as said on bootstrap-filestyle doc, we can transform our file input by calling the input this way:

<input type="file" class="filestyle">

We can also set options in data-attributes, but this is also not working at all:

<input type="file" class="filestyle"data-buttonBefore="true" data-buttonText="Please choose a file">

My problem is: even if bootstrap-filestyle is loaded correctly in generated bundle.js, my file input is not using bootstrap-filestyle. Just like the jquery plugin is not triggered.

I managed to get it working, by setting, in the component loading the html template file where i call this input file:

ngOnInit() {
    $(document).ready(function() {
      $(":file").filestyle();
    });
  }

But i'm not satisfied with this solution to call jquery directly. Is there any proper way to achieve the load of a jquery plugin through data-attributes?

Note: In a static html file where i simply load the three js files mentionned above, everything works properly without any call to jquery.

Rob
  • 14,746
  • 28
  • 47
  • 65
BlackHoleGalaxy
  • 9,160
  • 17
  • 59
  • 103
  • If a piece of Javascript code runs, then looks for existing elements with a class like your `filestyle`, the element must be within the DOM at that point in time. It works on your element in the document ready handler because that fires after the element is parsed and is placed in the DOM. Put the script AFTER the element is declared in the DOM and it should then work. – Mark Schultheiss Dec 07 '16 at 13:16
  • But what about doing so in the Angular2 context? I don't want to call the doc ready script in every component ngOnInit() in which I will set a file input. – BlackHoleGalaxy Dec 07 '16 at 13:45
  • This may help you with some ideas: http://stackoverflow.com/questions/16935095/correct-way-to-integrate-jquery-plugins-in-angularjs – Mark Schultheiss Dec 07 '16 at 16:58

0 Answers0