Skip to content

Instantly share code, notes, and snippets.

@jsanta
Last active January 5, 2021 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsanta/231bb5c65a1faf7571c846dfc49a3263 to your computer and use it in GitHub Desktop.
Save jsanta/231bb5c65a1faf7571c846dfc49a3263 to your computer and use it in GitHub Desktop.
Example Angular component that loads external libraries
import { RemoteLibraryService } from './../services/remote-library.service';
import { Component, OnInit, AfterViewInit, OnDestroy } from '@angular/core';
declare global {
var externalLibrary: any;
var otherExternalLibrary: any;
}
@Component({
selector: 'app-wrapper',
templateUrl: './wrapper.component.html',
styleUrls: ['./wrapper.component.scss']
})
export class WrapperComponent implements OnInit, AfterViewInit, OnDestroy {
constructor(
// ...
// IMPORTANT: remoteLibraryService MUST BE public
public remoteLibraryService: RemoteLibraryService) {}
ngOnInit() {
// ...
}
ngAfterViewInit(): void {
// ...
const scriptArray: Promise<any>[] = [
this.remoteLibraryService.loadScript('/assets/external-library.js').toPromise(),
this.remoteLibraryService.loadScript('https://external-site/scripts/other-external-library.js').toPromise(),
// you can use the remoteLibraryService to load any other script required or even css files
];
Promise.all(scriptArray).then(_ => {
console.log('All scripts loaded');
//...
// Use the loaded scripts
// ...
)};
}
ngOnDestroy() {
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment