0
votes

I am a bit new to Angular (version 8) and Typescript. I have code where users choose what type of chart, columns, and title to make a Google Chart after a click of a button.

I have tried to put the element in my chart.component.html inside a div with a specific id, and then appending google chart data after it is provided by the users with "innerHTML". I have all the data saved in local variables for type, data, title, etc.

Note: I have correctly imported GoogleChartComponent from 'angular-google-charts', as well as ViewChild from 'angular-core'.

I target the #here div element like this inside my chart.component.ts:

@ViewChild('googleChart', {static: false}) 
  googleChart: GoogleChartComponent;

This is in my chart.component.ts: ...


@Component({
...
})

export class ChartComponent implements OnInit {
...
createChart(){
this.here.nativeElement.innerHTML = "<google-chart [title]='title' [type]='type' [data]='data' [columnNames]='googleColumnNames' [options]='options' [width]='width' [height]='height'> </google-chart>";
}
...
}

And this is in my chart.component.html:

<button type="submit" id="chartButton" class="btn" (click)="createChart()">
            Create Chart
</button>

<div #here class="chartCreator"></div>

In the inspector, I see that the element has been appended inside the #here div element, but nothing is displayed and its width and height are shown as 0x0.

1

1 Answers

0
votes

I had the same problem but following this sample I stopped banging my head down.

Steps to follow:

First, on parent_component.ts I call the server and get data to plot:

export class ...{
    //First create an event child's can subscribe to
    updateIfItsYou: Subject<any> = new Subject();

    tellChild(who){
      this.updateIfItsYou.next(who);
    }

    function RequestDataFromServer(){
        //...received_data
        this.tellChild(received_data);
    }
}

now, moving to child component at the component.html file, simply put your google-chart object.

<google-chart #chart 
    width="500" height="300" 
    [title]="changingChart.title"  
    [type]="changingChart.type" 
    [data]="changingChart.data"
    [columnNames]="changingChart.columnNames"
    [options]="changingChart.options" >
</google-chart>

at the component.ts file:

public changingChart = {
    title: 'Chart Title',
    type: 'ColumnChart',
    data: [['1',0]], //this is just to avoid an error and allow for post-processing of data
    columnNames: ['Col1', 'Col2']
}

Suscribe child component to parent event:

@Input() changing: Subject<any> = new Subject();

and on ngAfterViewInit

this.changing.subscribe(v = > {
        //do whatever with v.. has the data received, like:
        this.changingChart.data = v.data
    }

and good to go. Hope it helps