user3408657
user3408657

Reputation: 189

Creating a directive for a external library in angular 2

I am just starting out with angular 2, and I have finished doing the basic quick start. Now I am just playing around with it and I have hit a bit of a block. I am trying to use dropzone.js.

I read somewhere else that you could use external libraries by just adding the script, and doing this in your component:

//index.html
<script src="node_modules/dropzone/dropzone.js"></script>

//app.component.ts
declare var Dropzone: any;
...
constructor(){
  var myDropzone = new Dropzone("div#myId", { url: "/file/post"});
  //I added a div with same ID as here to my template.
}

This didn't work for me. I also tried to use this angular 1 directive for dropzone.js as a reference for creating one for angular 2, but I am a bit lost, as I never worked with angular 1 before.

Upvotes: 2

Views: 2777

Answers (2)

Dmytro Bardai
Dmytro Bardai

Reputation: 154

Here it is working example:

import {Component} from 'angular2/core';

@Component({
  selector: 'dropzone',
  template: `
    <div id="myId" style="width: 200px; height: 200px; background-color: gray;">Drop down area</div>
    `
})
export class DropzoneComponent {
  private _dropzone: Dropzone;

  constructor() {
    System.import('./dropzone.js').then((dz) => this.initDropzone(dz));
  }

  initDropzone(d: any) {
    this._dropzone = new d('div#myId', { url: '/file/post'});
  }
}

plnkr.co

  1. Install dropzone package locally (for example with npm: npm install dropzone --save)
  2. Install typings for dropzone (typings install dropzone --save --ambient). It will allow you to work with strongly-typed variable.
  3. Take a look on promise after dropzone loading - you have to pass variable with function assigned to initializing method (initDropzone(d: any)).
  4. It is not needed to link dropzone script in index.html. Dropzone is loaded only when the certain component (DropzoneComponent) is loaded.

If you will have any questions you're welcome.

Upvotes: 2

Thierry Templier
Thierry Templier

Reputation: 202216

After having added the dropzone.js file in your index.html file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.2.0/dropzone.js"></script>

You could link it to the root element of a component:

@Component({
  selector: 'dropzone',
  template: `
    <div>Drop down area</div>
  `
})
export class DropZoneComponent {
  constructor(eltRef:ElementRef) {
    new Dropzone(eltRef.nativeElement, { url: "/file/post"});
  }
}

Here is a plunkr describing this: https://plnkr.co/edit/gV9fuWqALB7g7v7ZxWD4?p=preview.

Upvotes: 3

Related Questions