Last active
January 5, 2021 15:40
-
-
Save jsanta/231bb5c65a1faf7571c846dfc49a3263 to your computer and use it in GitHub Desktop.
Example Angular component that loads external libraries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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