angular - Angular2: load external javascript to component dynamically -
i trying load external library (javascript) 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 load...') let node = document.createelement('script'); node.src = url; node.type = 'text/javascript'; document.getelementsbytagname('head')[0].appendchild(node); } }
problem: image loaded without zoom/crop effect. inspected page , saw script added correctly in . refreshed page, no luck. had no error @ all. seems angular2 not activate script.
i tried workaround: putting script in index.html directly (this workaround return error when page not loaded yet)
<head> ... <script src="src/assets/js/mycropper.js"></script> </head>
photo loaded without zoom/crop effect @ start. after refresh page, zoom/crop effect activated. not practice scripts kept in index.html, @ least script works after refresh.
any suggestion appreciated.
Comments
Post a Comment