3

I am trying to load an external library (Javascript) to an Angular2 component (TypeScript).

Take example: https://github.com/fengyuanchen/cropperjs

My approach:

index.html

<head>
   <link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.css" rel="stylesheet">
   <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.js"></script>
</head>

myCropper.js

window.addEventListener('DOMContentLoaded', function () {
 var image = document.querySelector('#image');
 var cropper = new Cropper(image, {
    viewMode: 3,
    dragMode: 'move',
    autoCropArea: 1,
    restore: false,
    modal: false,
    guides: false,
    highlight: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false,
  });
 });

photo.component.ts

@Component({
selector: 'photo-crop',
template: `
    <div class="row">
      <img id="image" src="http://img01.ibnlive.in/ibnlive/uploads/875x584/jpg/2015/09/new-google-logo-010915.png" class="img-responsive"/>
    <div class="row">
    `,
styles: []
})
export class PhotoComponent {

public ngOnInit() {
    this.loadScript('src/assets/js/myCropper.js');           
    });
}

public loadScript(url) {
    console.log('preparing to load...')
    let node = document.createElement('script');
    node.src = url;
    node.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(node);
 }
}

Problem: the image is loaded without zoom/crop effect. I inspected the page and saw the script was added correctly in . I refreshed page, no luck. I had no error at all. It seems Angular2 does not activate the script.

I also tried a workaround: putting script in index.html directly (This workaround return error when the page is not loaded yet)

<head>
  ...
  <script src="src/assets/js/myCropper.js"></script>
</head>

Photo is loaded without zoom/crop effect at start. But after I refresh the page, zoom/crop effect is activated. This is not a good practice where all scripts kept in index.html, but at least the script works after refresh.

Any suggestion is appreciated.

Maciej Treder
  • 11,866
  • 5
  • 51
  • 74
franco phong
  • 2,219
  • 3
  • 26
  • 43
  • Here is the solution https://stackoverflow.com/questions/34489916/how-to-load-external-scripts-dynamically-in-angular/42766146#42766146 – Rahul Kumar Feb 09 '18 at 14:33
  • 1
    Possible duplicate of [How to load external scripts dynamically in Angular?](https://stackoverflow.com/questions/34489916/how-to-load-external-scripts-dynamically-in-angular) – Maciej Treder Feb 15 '18 at 09:48

0 Answers0