Chun
Chun

Reputation: 3

Angular - Render Google chart on a different page

Basically, I have two components page1 and page2 and I would like to draw a google Gantt chart on the second page. However, when switching to page2 nothing is rendered.

From what I understand you must load google chart inside the <head> element of index.html file, but because the container that should render the chart inside my component page2 is hidden at the start, google chart cannot find render it.

I have tried moving the google chart script to the html file of page2 but still no result.
Making page1 the container works but as soon as I switch pages it disappears when switching back to page1.

Here is my stackblitz with the code: https://stackblitz.com/edit/angular-button-routerlink-xglnar?file=src/index.html

Is there a way to work around that? Thank you!

Upvotes: 0

Views: 324

Answers (1)

TotallyNewb
TotallyNewb

Reputation: 4790

You can always look for some npm library that acts as a wrapper if you're unsure about how to do it properly - i.e. angular-google-charts. Note - I didn't test the library and whether / how it works.

You can also make changes yourself.

Note that you don't have place all the scripts in the head - important part is referencing the google loader:

<head>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>

Then you can use the global functions / variables imported from the file anywhere in your app. But, since Angular uses TypeScript, it will warn you that the 'google' object is not defined. To work around it, you can simply declare an empty const - which will be replaced on the runtime by the script imported from the google hosting:

declare const google;

Then you can simply put the required script in the OnInit hook of your component and it should work properly. Of course replacing the document.getElementById("chart_div") by Angular way of getting the container reference is preferred (i.e. ViewChild).

Updated stackblitz with working barebone minimum example: https://stackblitz.com/edit/angular-button-routerlink-6vzuyd

Upvotes: 0

Related Questions