0

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

1 Answer 1

0

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
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. Can you explain why is that happening?
My guess is that on window['__onGoogleLoaded'] the property loaded is successfully changed inside in the component class but the view is not updated, so we just added the ChangeDetectorRef to force the angular to detect any changes in the component class and re-draw your view

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.