angularexternal-script

Unable to access component after external script loaded


I'm trying to load Google API inside an angular6 app. After the load event has been fired, I can't really change anything in my component.

Have a look at the comments at the last 3 lines of the script

@Component({
  selector: 'my-app',
  template: '{{loaded}}',
})
export class AppComponent  {
  loaded = false;   
  constructor(){
    let node = document.createElement('script');
    node.src = 'https://apis.google.com/js/client.js?onload=__onGoogleLoaded';
    node.type = 'text/javascript';
    document.getElementsByTagName('head')[0].appendChild(node);

    window['__onGoogleLoaded'] = (ev) =>{
      console.log('here!!!!');// <----------------------------WORKING
      this.loaded = true;// <---------------------------------NOT WORKING
    }
    //this.loaded = true; <<----------------------------------WORKING
  }
}

https://stackblitz.com/edit/angular-qvwm3z?file=src%2Fapp%2Fapp.component.ts


Solution

  • Add a ChangeDetectorRef to force your app to check any changes in your component

    by doing this

      constructor(
        private changeRef: ChangeDetectorRef
      ){
        let node = document.createElement('script');
        node.src = 'https://apis.google.com/js/client.js?onload=__onGoogleLoaded';
        node.type = 'text/javascript';
        document.getElementsByTagName('head')[0].appendChild(node);
    
        window['__onGoogleLoaded'] = (ev) =>{
          console.log('here!!!!');// <----------------------------WORKING
          this.loaded = true;// <---------------------------------NOT WORKING
          this.changeRef.detectChanges(); <<---------------------------------- add this one
        }
        //this.loaded = true; <<----------------------------------WORKING
      }